From d02644f7c41150709795e57bfd40351b4da35a7b Mon Sep 17 00:00:00 2001 From: Kristóf Marussy Date: Sat, 23 Apr 2022 01:59:21 +0200 Subject: Preload safe debug shim (#29) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit In https://github.com/ferdium/ferdium-app/pull/23 we removed usages of the debug package due to an electron bug. This patch aims to restore some debug functionality by introducing a shim. The shim detect whether if it is being introduced in a preload script where the electron but would be triggered, and falls back to a simple replacement for debug. However, in the main and renderer processes, where a preload script is not being used, we still get full debug functionality. In this way, a module can be used both in a preload script and outside of it, while still preserving debug functionality whenever possible. Signed-off-by: Kristóf Marussy --- src/stores/AppStore.js | 37 +++++++++++++++--------------- src/stores/RecipesStore.js | 11 +++++---- src/stores/RequestStore.js | 5 ++--- src/stores/ServicesStore.js | 55 ++++++++++++++++++++++----------------------- src/stores/SettingsStore.js | 11 +++++---- src/stores/UserStore.js | 5 ++--- 6 files changed, 59 insertions(+), 65 deletions(-) (limited to 'src/stores') diff --git a/src/stores/AppStore.js b/src/stores/AppStore.js index 55cdce5f2..76956fdc7 100644 --- a/src/stores/AppStore.js +++ b/src/stores/AppStore.js @@ -29,8 +29,7 @@ import { import { openExternalUrl } from '../helpers/url-helpers'; import { sleep } from '../helpers/async-helpers'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:AppStore'); +const debug = require('../preload-safe-debug')('Ferdium:AppStore'); const mainWindow = getCurrentWindow(); @@ -196,7 +195,7 @@ export default class AppStore extends Store { // Handle deep linking (ferdium://) ipcRenderer.on('navigateFromDeepLink', (event, data) => { - console.log('Navigate from deep link', data); + debug('Navigate from deep link', data); let { url } = data; if (!url) return; @@ -218,28 +217,28 @@ export default class AppStore extends Store { this.isSystemDarkModeEnabled = nativeTheme.shouldUseDarkColors; ipcRenderer.on('isWindowFocused', (event, isFocused) => { - console.log('Setting is focused to', isFocused); + debug('Setting is focused to', isFocused); this.isFocused = isFocused; }); powerMonitor.on('suspend', () => { - console.log('System suspended starting timer'); + debug('System suspended starting timer'); this.timeSuspensionStart = moment(); }); powerMonitor.on('resume', () => { - console.log('System resumed, last suspended on', this.timeSuspensionStart); + debug('System resumed, last suspended on', this.timeSuspensionStart); this.actions.service.resetLastPollTimer(); if ( this.timeSuspensionStart.add(10, 'm').isBefore(moment()) && this.stores.settings.app.get('reloadAfterResume') ) { - console.log('Reloading services, user info and features'); + debug('Reloading services, user info and features'); setInterval(() => { - console.log('Reload app interval is starting'); + debug('Reload app interval is starting'); if (this.isOnline) { window.location.reload(); } @@ -251,7 +250,7 @@ export default class AppStore extends Store { // notifications got stuck after upgrade but forcing a notification // via `new Notification` triggered the permission request if (isMac && !localStorage.getItem(CATALINA_NOTIFICATION_HACK_KEY)) { - console.log('Triggering macOS Catalina notification permission trigger'); + debug('Triggering macOS Catalina notification permission trigger'); // eslint-disable-next-line no-new new window.Notification('Welcome to Ferdium 5', { body: 'Have a wonderful day & happy messaging.', @@ -320,7 +319,7 @@ export default class AppStore extends Store { const notification = new window.Notification(title, options); - console.log('New notification', title, options); + debug('New notification', title, options); notification.addEventListener('click', () => { if (serviceId) { @@ -342,7 +341,7 @@ export default class AppStore extends Store { } mainWindow.focus(); - console.log('Notification click handler'); + debug('Notification click handler'); } }); } @@ -371,10 +370,10 @@ export default class AppStore extends Store { try { if (enable) { - console.log('enabling launch on startup', executablePath); + debug('enabling launch on startup', executablePath); autoLauncher.enable(); } else { - console.log('disabling launch on startup'); + debug('disabling launch on startup'); autoLauncher.disable(); } } catch (error) { @@ -389,7 +388,7 @@ export default class AppStore extends Store { @action _checkForUpdates() { if (this.isOnline && this.stores.settings.app.automaticUpdates && (isMac || isWindows || process.env.APPIMAGE)) { - console.log('_checkForUpdates: sending event to autoUpdate:check'); + debug('_checkForUpdates: sending event to autoUpdate:check'); this.updateStatus = this.updateStatusTypes.CHECKING; ipcRenderer.send('autoUpdate', { action: 'check', @@ -402,7 +401,7 @@ export default class AppStore extends Store { } @action _installUpdate() { - console.log('_installUpdate: sending event to autoUpdate:install'); + debug('_installUpdate: sending event to autoUpdate:install'); ipcRenderer.send('autoUpdate', { action: 'install', }); @@ -488,7 +487,7 @@ export default class AppStore extends Store { } moment.locale(this.locale); - console.log(`Set locale to "${this.locale}"`); + debug(`Set locale to "${this.locale}"`); } _getDefaultLocale() { @@ -542,7 +541,7 @@ export default class AppStore extends Store { this.autoLaunchOnStart = await this._checkAutoStart(); if (this.stores.settings.all.stats.appStarts === 1) { - console.log('Set app to launch on start'); + debug('Set app to launch on start'); this.actions.app.launchOnStartup({ enable: true, }); @@ -554,9 +553,9 @@ export default class AppStore extends Store { } async _systemDND() { - console.log('Checking if Do Not Disturb Mode is on'); + debug('Checking if Do Not Disturb Mode is on'); const dnd = await ipcRenderer.invoke('get-dnd'); - console.log('Do not disturb mode is', dnd); + debug('Do not disturb mode is', dnd); if ( dnd !== this.stores.settings.all.app.isAppMuted && !this.isSystemMuteOverridden diff --git a/src/stores/RecipesStore.js b/src/stores/RecipesStore.js index d39b87401..3d3a506cc 100644 --- a/src/stores/RecipesStore.js +++ b/src/stores/RecipesStore.js @@ -8,8 +8,7 @@ import Request from './lib/Request'; import { matchRoute } from '../helpers/routing-helpers'; import { asarRecipesPath } from '../helpers/asar-helpers'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:RecipeStore'); +const debug = require('../preload-safe-debug')('Ferdium:RecipeStore'); export default class RecipesStore extends Store { @observable allRecipesRequest = new CachedRequest(this.api.recipes, 'all'); @@ -48,7 +47,7 @@ export default class RecipesStore extends Store { return activeRecipe; } - console.log(`Recipe ${match.id} not installed`); + debug(`Recipe ${match.id} not installed`); } return null; @@ -79,7 +78,7 @@ export default class RecipesStore extends Store { const recipes = {}; // Hackfix, reference this.all to fetch services - console.log(`Check Recipe updates for ${this.all.map(recipe => recipe.id)}`); + debug(`Check Recipe updates for ${this.all.map(recipe => recipe.id)}`); for (const r of recipeIds) { const recipe = this.one(r); @@ -108,7 +107,7 @@ export default class RecipesStore extends Store { } const updates = [...remoteUpdates, ...localUpdates]; - console.log( + debug( 'Got update information (local, remote):', localUpdates, remoteUpdates, @@ -146,7 +145,7 @@ export default class RecipesStore extends Store { if (!this.stores.recipes.isInstalled(recipeId)) { router.push('/settings/recipes'); - console.log(`Recipe ${recipeId} is not installed, trying to install it`); + debug(`Recipe ${recipeId} is not installed, trying to install it`); const recipe = await this.installRecipeRequest.execute(recipeId) ._promise; diff --git a/src/stores/RequestStore.js b/src/stores/RequestStore.js index a6991409c..8b716ac81 100644 --- a/src/stores/RequestStore.js +++ b/src/stores/RequestStore.js @@ -4,8 +4,7 @@ import ms from 'ms'; import Store from './lib/Store'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:RequestsStore'); +const debug = require('../preload-safe-debug')('Ferdium:RequestsStore'); export default class RequestStore extends Store { @observable userInfoRequest; @@ -66,7 +65,7 @@ export default class RequestStore extends Store { } this._autoRetry(); - console.log(`Retry required requests delayed in ${delay / 1000}s`); + debug(`Retry required requests delayed in ${delay / 1000}s`); }, delay); } } diff --git a/src/stores/ServicesStore.js b/src/stores/ServicesStore.js index 3847536ca..c8042e9de 100644 --- a/src/stores/ServicesStore.js +++ b/src/stores/ServicesStore.js @@ -19,8 +19,7 @@ import { DEFAULT_SERVICE_SETTINGS, KEEP_WS_LOADED_USID } from '../config'; import { SPELLCHECKER_LOCALES } from '../i18n/languages'; import { ferdiumVersion } from '../environment-remote'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:ServiceStore'); +const debug = require('../preload-safe-debug')('Ferdium:ServiceStore'); export default class ServicesStore extends Store { @observable allServicesRequest = new CachedRequest(this.api.services, 'all'); @@ -213,7 +212,7 @@ export default class ServicesStore extends Store { serviceMaintenanceTick = debounce(() => { this._serviceMaintenance(); this.serviceMaintenanceTick(); - console.log('Service maintenance tick'); + debug('Service maintenance tick'); }, ms('10s')); /** @@ -251,7 +250,7 @@ export default class ServicesStore extends Store { // If service did not reply for more than 1m try to reload. if (!service.isActive) { if (this.stores.app.isOnline && service.lostRecipeReloadAttempt < 3) { - console.log( + debug( `Reloading service: ${service.name} (${service.id}). Attempt: ${service.lostRecipeReloadAttempt}`, ); // service.webview.reload(); @@ -260,7 +259,7 @@ export default class ServicesStore extends Store { service.lostRecipeConnection = false; } } else { - console.log(`Service lost connection: ${service.name} (${service.id}).`); + debug(`Service lost connection: ${service.name} (${service.id}).`); service.lostRecipeConnection = true; } } else { @@ -364,7 +363,7 @@ export default class ServicesStore extends Store { return activeService; } - console.log('Service not available'); + debug('Service not available'); } return null; @@ -398,9 +397,9 @@ export default class ServicesStore extends Store { skipCleanup = false, }) { if (!this.stores.recipes.isInstalled(recipeId)) { - console.log(`Recipe "${recipeId}" is not installed, installing recipe`); + debug(`Recipe "${recipeId}" is not installed, installing recipe`); await this.stores.recipes._install({ recipeId }); - console.log(`Recipe "${recipeId}" installed`); + debug(`Recipe "${recipeId}" installed`); } // set default values for serviceData @@ -617,7 +616,7 @@ export default class ServicesStore extends Store { if (service) { service.isActive = false; } else { - console.log('No service is active'); + debug('No service is active'); } } @@ -660,7 +659,7 @@ export default class ServicesStore extends Store { service.webview = webview; if (!service.isAttached) { - console.log('Webview is not attached, initializing'); + debug('Webview is not attached, initializing'); service.initializeWebViewEvents({ handleIPCMessage: this.actions.service.handleIPCMessage, openWindow: this.actions.service.openWindow, @@ -709,7 +708,7 @@ export default class ServicesStore extends Store { } } } else { - console.log('No service is active'); + debug('No service is active'); } } else { this.allServicesRequest.invalidate(); @@ -728,7 +727,7 @@ export default class ServicesStore extends Store { // eslint-disable-next-line default-case switch (channel) { case 'hello': { - console.log('Received hello event from', serviceId); + debug('Received hello event from', serviceId); this._initRecipePolling(service.id); this._initializeServiceRecipeInWebview(serviceId); @@ -742,7 +741,7 @@ export default class ServicesStore extends Store { break; } case 'message-counts': { - console.log(`Received unread message info from '${serviceId}'`, args[0]); + debug(`Received unread message info from '${serviceId}'`, args[0]); this.actions.service.setUnreadMessageCount({ serviceId, @@ -755,7 +754,7 @@ export default class ServicesStore extends Store { break; } case 'active-dialog-title': { - console.log(`Received active dialog title from '${serviceId}'`, args[0]); + debug(`Received active dialog title from '${serviceId}'`, args[0]); this.actions.service.setDialogTitle({ serviceId, @@ -920,7 +919,7 @@ export default class ServicesStore extends Store { serviceId: service.id, }); } else { - console.log('No service is active'); + debug('No service is active'); } } @@ -1028,7 +1027,7 @@ export default class ServicesStore extends Store { if (service) { this._openDevTools({ serviceId: service.id }); } else { - console.log('No service is active'); + debug('No service is active'); } } @@ -1038,7 +1037,7 @@ export default class ServicesStore extends Store { return; } - console.log(`Hibernate ${service.name}`); + debug(`Hibernate ${service.name}`); service.isHibernationRequested = true; service.lastHibernated = Date.now(); @@ -1048,7 +1047,7 @@ export default class ServicesStore extends Store { const now = Date.now(); const service = this.one(serviceId); const automaticTag = automatic ? ' automatically ' : ' '; - console.log( + debug( `Waking up${automaticTag}from service hibernation for ${service.name}`, ); @@ -1069,8 +1068,8 @@ export default class ServicesStore extends Store { // const mainStrategy = this.stores.settings.all.app.hibernationStrategy; let strategy = this.stores.settings.all.app.wakeUpHibernationStrategy; - console.log(`wakeUpHibernationStrategy = ${strategy}`); - console.log(`hibernationStrategy = ${mainStrategy}`); + debug(`wakeUpHibernationStrategy = ${strategy}`); + debug(`hibernationStrategy = ${mainStrategy}`); if (!strategy || strategy < 1) { strategy = this.stores.settings.all.app.hibernationStrategy; } @@ -1082,16 +1081,16 @@ export default class ServicesStore extends Store { ) { // Add 10 additional seconds 50% of the time. splay = 10; - console.log('Added splay'); + debug('Added splay'); } else { - console.log('skipping splay'); + debug('skipping splay'); } // wake up again in strategy + splay seconds instead of mainStrategy seconds. service.lastUsed = now - ms(`${mainStrategy - (strategy + splay)}s`); } else { service.lastUsed = now; } - console.log( + debug( `Setting service.lastUsed to ${service.lastUsed} (${ (now - service.lastUsed) / 1000 }s ago)`, @@ -1101,7 +1100,7 @@ export default class ServicesStore extends Store { } @action _resetLastPollTimer({ serviceId = null }) { - console.log( + debug( `Reset last poll timer for ${ serviceId ? `service: "${serviceId}"` : 'all services' }`, @@ -1132,7 +1131,7 @@ export default class ServicesStore extends Store { service.dialogTitle ? ` - ${service.dialogTitle}` : '' } ${service._webview ? `- ${service._webview.getTitle()}` : ''}`; } else { - console.log('No service is active'); + debug('No service is active'); } } @@ -1146,7 +1145,7 @@ export default class ServicesStore extends Store { }, }); } else { - console.log('No service is active'); + debug('No service is active'); } } @@ -1262,7 +1261,7 @@ export default class ServicesStore extends Store { this.allDisplayed.findIndex(service => service.isActive) === -1 && this.allDisplayed.length > 0 ) { - console.log('No active service found, setting active service to index 0'); + debug('No active service found, setting active service to index 0'); this._setActive({ serviceId: this.allDisplayed[0].id }); } @@ -1278,7 +1277,7 @@ export default class ServicesStore extends Store { JSON.stringify(service.shareWithWebview), ); - console.log('Initialize recipe', service.recipe.id, service.name); + debug('Initialize recipe', service.recipe.id, service.name); service.webview.send( 'initialize-recipe', { diff --git a/src/stores/SettingsStore.js b/src/stores/SettingsStore.js index 3ba791239..6b6b77454 100644 --- a/src/stores/SettingsStore.js +++ b/src/stores/SettingsStore.js @@ -11,8 +11,7 @@ import { hash } from '../helpers/password-helpers'; import Request from './lib/Request'; import Store from './lib/Store'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:SettingsStore'); +const debug = require('../preload-safe-debug')('Ferdium:SettingsStore'); export default class SettingsStore extends Store { @observable updateAppSettingsRequest = new Request( @@ -95,7 +94,7 @@ export default class SettingsStore extends Store { } }); } - console.log('Get appSettings resolves', resp.type, resp.data); + debug('Get appSettings resolves', resp.type, resp.data); Object.assign(this._fileSystemSettingsCache[resp.type], resp.data); this.loaded = true; ipcRenderer.send('initialAppSettings', resp); @@ -147,10 +146,10 @@ export default class SettingsStore extends Store { @action async _update({ type, data }) { const appSettings = this.all; if (!this.fileSystemSettingsTypes.includes(type)) { - console.log('Update settings', type, data, this.all); + debug('Update settings', type, data, this.all); localStorage.setItem(type, Object.assign(appSettings[type], data)); } else { - console.log('Update settings on file system', type, data); + debug('Update settings on file system', type, data); ipcRenderer.send('updateAppSettings', { type, data, @@ -201,7 +200,7 @@ export default class SettingsStore extends Store { }); } - console.log('Migrated updates settings'); + debug('Migrated updates settings'); }); this._ensureMigrationAndMarkDone('5.6.0-beta.6-settings', () => { diff --git a/src/stores/UserStore.js b/src/stores/UserStore.js index 8c413a065..661c03e2c 100644 --- a/src/stores/UserStore.js +++ b/src/stores/UserStore.js @@ -10,8 +10,7 @@ import Store from './lib/Store'; import Request from './lib/Request'; import CachedRequest from './lib/CachedRequest'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:UserStore'); +const debug = require('../preload-safe-debug')('Ferdium:UserStore'); // TODO: split stores into UserStore and AuthStore export default class UserStore extends Store { @@ -395,7 +394,7 @@ export default class UserStore extends Store { } if (!this.data.locale) { - console.log('Migrate "locale" to user data'); + debug('Migrate "locale" to user data'); this.actions.user.update({ userData: { locale: this.stores.app.locale, -- cgit v1.2.3-54-g00ecf