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 --- CONTRIBUTING.md | 2 + src/api/server/LocalApi.ts | 9 ++- src/api/server/ServerApi.ts | 61 ++++++++++---------- src/components/services/content/ServiceWebview.js | 9 ++- .../settings/settings/EditSettingsForm.js | 2 +- src/containers/settings/EditSettingsScreen.js | 2 +- src/electron/Settings.ts | 2 +- src/electron/ipc-api/autoUpdate.ts | 2 +- src/electron/ipc-api/cld.ts | 2 +- src/electron/ipc-api/dnd.ts | 2 +- src/electron/ipc-api/download.ts | 7 +-- src/electron/ipc-api/sessionStorage.ts | 9 ++- src/electron/macOSPermissions.ts | 19 +++---- src/features/basicAuth/index.ts | 2 +- src/features/basicAuth/mainIpcHandler.ts | 2 +- src/features/basicAuth/store.ts | 2 +- src/features/communityRecipes/store.ts | 7 +-- src/features/publishDebugInfo/Component.js | 2 +- src/features/publishDebugInfo/index.ts | 2 +- src/features/quickSwitch/index.ts | 2 +- src/features/serviceProxy/index.ts | 11 ++-- src/features/todos/preload.ts | 7 +-- src/features/todos/store.js | 23 ++++---- src/features/workspaces/api.ts | 19 +++---- src/features/workspaces/store.js | 9 ++- src/helpers/url-helpers.ts | 7 +-- src/index.html | 3 + src/index.ts | 66 +++++++++++----------- .../app/Controllers/Http/RecipeController.js | 2 +- src/models/Service.js | 31 +++++----- src/models/UserAgent.js | 11 ++-- src/preload-safe-debug.ts | 29 ++++++++++ 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 +- src/webview/badge.ts | 5 +- src/webview/darkmode.ts | 7 +-- src/webview/dialogTitle.ts | 5 +- src/webview/lib/RecipeWebview.ts | 11 ++-- src/webview/notifications.ts | 5 +- src/webview/recipe.js | 57 +++++++++---------- src/webview/sessionHandler.ts | 7 +-- src/webview/spellchecker.ts | 9 ++- 46 files changed, 300 insertions(+), 295 deletions(-) create mode 100644 src/preload-safe-debug.ts diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 78b9a36be..8f1b19685 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -202,6 +202,8 @@ DEBUG_COLORS=1 DEBUG=Ferdium:* npm run start:all-dev ``` Note: please prefer [`debug()`](https://github.com/visionmedia/debug) over `console.log()`. +However, due to an [Electron bug](https://github.com/electron/electron/issues/31689), using `require('debug')` directly is dangerous and can lead to data loss in services. +Please use the `src/preload-safe-debug` module instead until the bug gets fixed. ### Styleguide diff --git a/src/api/server/LocalApi.ts b/src/api/server/LocalApi.ts index 28028bf80..a292bc42d 100644 --- a/src/api/server/LocalApi.ts +++ b/src/api/server/LocalApi.ts @@ -4,15 +4,14 @@ import fastFolderSize from 'fast-folder-size'; import { getServicePartitionsDirectory } from '../../helpers/service-helpers'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:LocalApi'); +const debug = require('../../preload-safe-debug')('Ferdium:LocalApi'); export default class LocalApi { // Settings getAppSettings(type: string) { return new Promise(resolve => { ipcRenderer.once('appSettings', (_event, resp) => { - console.log('LocalApi::getAppSettings resolves', resp.type, resp.data); + debug('LocalApi::getAppSettings resolves', resp.type, resp.data); resolve(resp); }); @@ -21,7 +20,7 @@ export default class LocalApi { } async updateAppSettings(type: string, data: any) { - console.log('LocalApi::updateAppSettings resolves', type, data); + debug('LocalApi::updateAppSettings resolves', type, data); ipcRenderer.send('updateAppSettings', { type, data, @@ -40,7 +39,7 @@ export default class LocalApi { reject(err); } - console.log('LocalApi::getAppCacheSize resolves', bytes); + debug('LocalApi::getAppCacheSize resolves', bytes); resolve(bytes); }, ); diff --git a/src/api/server/ServerApi.ts b/src/api/server/ServerApi.ts index dc29c7b89..935d7de3d 100644 --- a/src/api/server/ServerApi.ts +++ b/src/api/server/ServerApi.ts @@ -35,8 +35,7 @@ import { import { removeServicePartitionDirectory } from '../../helpers/service-helpers'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:ServerApi'); +const debug = require('../../preload-safe-debug')('Ferdium:ServerApi'); module.paths.unshift(getDevRecipeDirectory(), getRecipeDirectory()); @@ -62,7 +61,7 @@ export default class ServerApi { } const u = await request.json(); - console.log('ServerApi::login resolves', u); + debug('ServerApi::login resolves', u); return u.token; } @@ -80,7 +79,7 @@ export default class ServerApi { } const u = await request.json(); - console.log('ServerApi::signup resolves', u); + debug('ServerApi::signup resolves', u); return u.token; } @@ -93,7 +92,7 @@ export default class ServerApi { throw new Error(request.statusText); } - console.log('ServerApi::inviteUser'); + debug('ServerApi::inviteUser'); return true; } @@ -113,7 +112,7 @@ export default class ServerApi { } const r = await request.json(); - console.log('ServerApi::retrievePassword'); + debug('ServerApi::retrievePassword'); return r; } @@ -129,7 +128,7 @@ export default class ServerApi { const data = await request.json(); const user = new UserModel(data); - console.log('ServerApi::userInfo resolves', user); + debug('ServerApi::userInfo resolves', user); return user; } @@ -147,7 +146,7 @@ export default class ServerApi { const user = Object.assign(updatedData, { data: new UserModel(updatedData.data), }); - console.log('ServerApi::updateUserInfo resolves', user); + debug('ServerApi::updateUserInfo resolves', user); return user; } @@ -160,7 +159,7 @@ export default class ServerApi { } const data = await request.json(); - console.log('ServerApi::deleteAccount resolves', data); + debug('ServerApi::deleteAccount resolves', data); return data; } @@ -178,7 +177,7 @@ export default class ServerApi { const services = await this._mapServiceModels(data); const filteredServices = services.filter(service => !!service); - console.log('ServerApi::getServices resolves', filteredServices); + debug('ServerApi::getServices resolves', filteredServices); return filteredServices; } @@ -205,7 +204,7 @@ export default class ServerApi { data: await this._prepareServiceModel(serviceData.data), }); - console.log('ServerApi::createService resolves', service); + debug('ServerApi::createService resolves', service); return service; } @@ -231,7 +230,7 @@ export default class ServerApi { data: await this._prepareServiceModel(serviceData.data), }); - console.log('ServerApi::updateService resolves', service); + debug('ServerApi::updateService resolves', service); return service; } @@ -271,7 +270,7 @@ export default class ServerApi { throw new Error(request.statusText); } const serviceData = await request.json(); - console.log('ServerApi::reorderService resolves', serviceData); + debug('ServerApi::reorderService resolves', serviceData); return serviceData; } @@ -286,7 +285,7 @@ export default class ServerApi { removeServicePartitionDirectory(id, true); - console.log('ServerApi::deleteService resolves', data); + debug('ServerApi::deleteService resolves', data); return data; } @@ -299,7 +298,7 @@ export default class ServerApi { const data = await request.json(); const features = data; - console.log('ServerApi::getDefaultFeatures resolves', features); + debug('ServerApi::getDefaultFeatures resolves', features); return features; } @@ -315,7 +314,7 @@ export default class ServerApi { const data = await request.json(); const features = data; - console.log('ServerApi::getFeatures resolves', features); + debug('ServerApi::getFeatures resolves', features); return features; } @@ -340,7 +339,7 @@ export default class ServerApi { // eslint-disable-next-line unicorn/prefer-spread this.recipes = this.recipes.concat(this._getDevRecipes()); - console.log('StubServerApi::getInstalledRecipes resolves', this.recipes); + debug('StubServerApi::getInstalledRecipes resolves', this.recipes); return this.recipes; } @@ -353,7 +352,7 @@ export default class ServerApi { throw new Error(request.statusText); } const recipes = await request.json(); - console.log('ServerApi::getRecipeUpdates resolves', recipes); + debug('ServerApi::getRecipeUpdates resolves', recipes); return recipes; } @@ -363,7 +362,7 @@ export default class ServerApi { if (!request.ok) throw new Error(request.statusText); const data = await request.json(); const recipePreviews = this._mapRecipePreviewModel(data); - console.log('ServerApi::getRecipes resolves', recipePreviews); + debug('ServerApi::getRecipes resolves', recipePreviews); return recipePreviews; } @@ -375,7 +374,7 @@ export default class ServerApi { // data = this._addLocalRecipesToPreviews(data); const recipePreviews = this._mapRecipePreviewModel(data); - console.log('ServerApi::getFeaturedRecipes resolves', recipePreviews); + debug('ServerApi::getFeaturedRecipes resolves', recipePreviews); return recipePreviews; } @@ -386,7 +385,7 @@ export default class ServerApi { const data = await request.json(); const recipePreviews = this._mapRecipePreviewModel(data); - console.log('ServerApi::searchRecipePreviews resolves', recipePreviews); + debug('ServerApi::searchRecipePreviews resolves', recipePreviews); return recipePreviews; } @@ -402,21 +401,21 @@ export default class ServerApi { let archivePath: PathOrFileDescriptor; if (pathExistsSync(internalRecipeFile)) { - console.log('[ServerApi::getRecipePackage] Using internal recipe file'); + debug('[ServerApi::getRecipePackage] Using internal recipe file'); archivePath = internalRecipeFile; } else { - console.log('[ServerApi::getRecipePackage] Downloading recipe from server'); + debug('[ServerApi::getRecipePackage] Downloading recipe from server'); archivePath = tempArchivePath; const packageUrl = `${apiBase()}/recipes/download/${recipeId}`; const res = await window.fetch(packageUrl); - console.log('Recipe downloaded', recipeId); + debug('Recipe downloaded', recipeId); const blob = await res.blob(); const buffer = await blob.arrayBuffer(); writeFileSync(tempArchivePath, Buffer.from(buffer)); } - console.log(archivePath); + debug(archivePath); await sleep(10); @@ -427,7 +426,7 @@ export default class ServerApi { preservePaths: true, unlink: true, preserveOwner: false, - onwarn: x => console.log('warn', recipeId, x), + onwarn: x => debug('warn', recipeId, x), }); await sleep(10); @@ -457,7 +456,7 @@ export default class ServerApi { if (!request.ok) { throw new Error(request.statusText); } - console.log('ServerApi::healthCheck resolves'); + debug('ServerApi::healthCheck resolves'); } async getLegacyServices() { @@ -484,7 +483,7 @@ export default class ServerApi { }), ); - console.log('ServerApi::getLegacyServices resolves', services); + debug('ServerApi::getLegacyServices resolves', services); return services; } } catch { @@ -517,7 +516,7 @@ export default class ServerApi { return new ServiceModel(service, recipe); } catch (error) { - console.log(error); + debug(error); return null; } } @@ -540,7 +539,7 @@ export default class ServerApi { await this.getRecipePackage(recipeId); - console.log('Rerun ServerAPI::getInstalledRecipes'); + debug('Rerun ServerAPI::getInstalledRecipes'); await this.getInstalledRecipes(); recipe = this.recipes.find(r => r.id === recipeId); @@ -605,7 +604,7 @@ export default class ServerApi { return recipes; } catch { - console.log('Could not load dev recipes'); + debug('Could not load dev recipes'); return false; } } diff --git a/src/components/services/content/ServiceWebview.js b/src/components/services/content/ServiceWebview.js index f1c4251ba..6d6089793 100644 --- a/src/components/services/content/ServiceWebview.js +++ b/src/components/services/content/ServiceWebview.js @@ -7,8 +7,7 @@ import { join } from 'path'; import ServiceModel from '../../../models/Service'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:Services'); +const debug = require('../../../preload-safe-debug')('Ferdium:Services'); class ServiceWebview extends Component { static propTypes = { @@ -28,7 +27,7 @@ class ServiceWebview extends Component { () => { if (this.webview && this.webview.view) { this.webview.view.addEventListener('console-message', e => { - console.log('Service logged a message:', e.message); + debug('Service logged a message:', e.message); }); this.webview.view.addEventListener('did-navigate', () => { if (this.props.service._webview) { @@ -51,7 +50,7 @@ class ServiceWebview extends Component { refocusWebview = () => { const { webview } = this; - console.log('Refocus Webview is called', this.props.service); + debug('Refocus Webview is called', this.props.service); if (!webview) return; if (this.props.service.isActive) { webview.view.blur(); @@ -64,7 +63,7 @@ class ServiceWebview extends Component { } ${`- ${this.props.service._webview.getTitle()}`}`; }, 100); } else { - console.log('Refocus not required - Not active service'); + debug('Refocus not required - Not active service'); } }; diff --git a/src/components/settings/settings/EditSettingsForm.js b/src/components/settings/settings/EditSettingsForm.js index f08705bed..c236dd295 100644 --- a/src/components/settings/settings/EditSettingsForm.js +++ b/src/components/settings/settings/EditSettingsForm.js @@ -31,7 +31,7 @@ import { openPath } from '../../../helpers/url-helpers'; import globalMessages from '../../../i18n/globalMessages'; import { Icon } from '../../ui/icon'; -const debug = require('debug')('Ferdium:EditSettingsForm'); +const debug = require('../../../preload-safe-debug')('Ferdium:EditSettingsForm'); const messages = defineMessages({ headlineGeneral: { diff --git a/src/containers/settings/EditSettingsScreen.js b/src/containers/settings/EditSettingsScreen.js index 87d1f1456..e4f7c13f1 100644 --- a/src/containers/settings/EditSettingsScreen.js +++ b/src/containers/settings/EditSettingsScreen.js @@ -37,7 +37,7 @@ import globalMessages from '../../i18n/globalMessages'; import WorkspacesStore from '../../features/workspaces/store'; import ServicesStore from '../../stores/ServicesStore'; -const debug = require('debug')('Ferdium:EditSettingsScreen'); +const debug = require('../../preload-safe-debug')('Ferdium:EditSettingsScreen'); const messages = defineMessages({ autoLaunchOnStart: { diff --git a/src/electron/Settings.ts b/src/electron/Settings.ts index 0956ea486..de010b9a3 100644 --- a/src/electron/Settings.ts +++ b/src/electron/Settings.ts @@ -2,7 +2,7 @@ import { observable, toJS } from 'mobx'; import { pathExistsSync, outputJsonSync, readJsonSync } from 'fs-extra'; import { userDataPath } from '../environment-remote'; -const debug = require('debug')('Ferdium:Settings'); +const debug = require('../preload-safe-debug')('Ferdium:Settings'); export default class Settings { type = ''; diff --git a/src/electron/ipc-api/autoUpdate.ts b/src/electron/ipc-api/autoUpdate.ts index 930644816..839f1f117 100644 --- a/src/electron/ipc-api/autoUpdate.ts +++ b/src/electron/ipc-api/autoUpdate.ts @@ -2,7 +2,7 @@ import { app, ipcMain, BrowserWindow } from 'electron'; import { autoUpdater } from 'electron-updater'; import { isMac, isWindows } from '../../environment'; -const debug = require('debug')('Ferdium:ipcApi:autoUpdate'); +const debug = require('../../preload-safe-debug')('Ferdium:ipcApi:autoUpdate'); export default (params: { mainWindow: BrowserWindow; settings: any }) => { const enableUpdate = Boolean(params.settings.app.get('automaticUpdates')); diff --git a/src/electron/ipc-api/cld.ts b/src/electron/ipc-api/cld.ts index 8918b016f..a6332e22d 100644 --- a/src/electron/ipc-api/cld.ts +++ b/src/electron/ipc-api/cld.ts @@ -2,7 +2,7 @@ import { ipcMain } from 'electron'; // @ts-ignore import cld from 'cld'; -const debug = require('debug')('Ferdium:ipcApi:cld'); +const debug = require('../../preload-safe-debug')('Ferdium:ipcApi:cld'); export default async () => { ipcMain.handle('detect-language', async (_event, { sample }) => { diff --git a/src/electron/ipc-api/dnd.ts b/src/electron/ipc-api/dnd.ts index 54a325db2..6b1777367 100644 --- a/src/electron/ipc-api/dnd.ts +++ b/src/electron/ipc-api/dnd.ts @@ -3,7 +3,7 @@ import { isMac } from '../../environment'; const { getDoNotDisturb } = require('macos-notification-state'); -const debug = require('debug')('Ferdium:ipcApi:dnd'); +const debug = require('../../preload-safe-debug')('Ferdium:ipcApi:dnd'); export default async () => { ipcMain.handle('get-dnd', async () => { diff --git a/src/electron/ipc-api/download.ts b/src/electron/ipc-api/download.ts index 3631e8fee..21af0d045 100644 --- a/src/electron/ipc-api/download.ts +++ b/src/electron/ipc-api/download.ts @@ -4,8 +4,7 @@ import mime from 'mime-types'; import { writeFileSync } from 'fs-extra'; import { PathLike } from 'fs'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:ipcApi:download'); +const debug = require('../../preload-safe-debug')('Ferdium:ipcApi:download'); function decodeBase64Image(dataString: string) { const matches = dataString.match(/^data:([+/A-Za-z-]+);base64,(.+)$/); @@ -28,7 +27,7 @@ export default (params: { mainWindow: BrowserWindow }) => { const dl = await download(win!, url, { saveAs: true, }); - console.log('File saved to', dl.savePath); + debug('File saved to', dl.savePath); } else { const extension = mime.extension(fileOptions.mime); const filename = `${fileOptions.name}.${extension}`; @@ -47,7 +46,7 @@ export default (params: { mainWindow: BrowserWindow }) => { 'binary', ); - console.log('File blob saved to', saveDialog.filePath); + debug('File blob saved to', saveDialog.filePath); } catch (error) { console.error(error); } diff --git a/src/electron/ipc-api/sessionStorage.ts b/src/electron/ipc-api/sessionStorage.ts index 96acacd12..2a9f4b4d1 100644 --- a/src/electron/ipc-api/sessionStorage.ts +++ b/src/electron/ipc-api/sessionStorage.ts @@ -2,8 +2,7 @@ import { ipcMain, Session, session } from 'electron'; import { TODOS_PARTITION_ID } from '../../config'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:ipcApi:sessionStorage'); +const debug = require('../../preload-safe-debug')('Ferdium:ipcApi:sessionStorage'); function deduceSession(serviceId: string | undefined | null): Session { if (serviceId) { @@ -22,14 +21,14 @@ export default async () => { const serviceSession = deduceSession(serviceId); serviceSession.flushStorageData(); if (targetsToClear) { - console.log('Clearing targets:', targetsToClear); + debug('Clearing targets:', targetsToClear); serviceSession.clearStorageData(targetsToClear); } else { - console.log('Clearing all targets'); + debug('Clearing all targets'); serviceSession.clearStorageData(); } } catch (error) { - console.log(error); + debug(error); } }); diff --git a/src/electron/macOSPermissions.ts b/src/electron/macOSPermissions.ts index 07caaaada..2415534e5 100644 --- a/src/electron/macOSPermissions.ts +++ b/src/electron/macOSPermissions.ts @@ -6,12 +6,11 @@ import { dirname } from 'path'; import { askForScreenCaptureAccess } from 'node-mac-permissions'; import { userDataPath } 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:macOSPermissions'); +const debug = require('../preload-safe-debug')('Ferdium:macOSPermissions'); const isExplicitScreenCapturePermissionReqd = macosVersion.isGreaterThanOrEqualTo('10.15'); -console.log( +debug( `Should check explicitly for screen-capture permissions: ${isExplicitScreenCapturePermissionReqd}`, ); @@ -22,7 +21,7 @@ function hasPromptedForScreenCapturePermission(): string | boolean { return false; } - console.log('Checking if status file exists'); + debug('Checking if status file exists'); return filePath && pathExistsSync(filePath); } @@ -32,7 +31,7 @@ function hasScreenCapturePermissionAlreadyBeenGranted(): boolean { } const screenCaptureStatus = systemPreferences.getMediaAccessStatus('screen'); - console.log(`screen-capture permissions status: ${screenCaptureStatus}`); + debug(`screen-capture permissions status: ${screenCaptureStatus}`); return screenCaptureStatus === 'granted'; } @@ -50,18 +49,18 @@ function createStatusFile() { } export const askFormacOSPermissions = async (mainWindow: BrowserWindow) => { - console.log('Checking camera & microphone permissions'); + debug('Checking camera & microphone permissions'); systemPreferences.askForMediaAccess('camera'); systemPreferences.askForMediaAccess('microphone'); if (hasScreenCapturePermissionAlreadyBeenGranted()) { - console.log('Already obtained screen-capture permissions - writing status file'); + debug('Already obtained screen-capture permissions - writing status file'); createStatusFile(); return; } if (!hasPromptedForScreenCapturePermission()) { - console.log('Checking screen capture permissions'); + debug('Checking screen capture permissions'); const { response } = await dialog.showMessageBox(mainWindow, { type: 'info', @@ -74,11 +73,11 @@ export const askFormacOSPermissions = async (mainWindow: BrowserWindow) => { }); if (response === 0) { - console.log('Asking for access'); + debug('Asking for access'); askForScreenCaptureAccess(); createStatusFile(); } else if (response === 1) { - console.log("Don't ask again"); + debug("Don't ask again"); createStatusFile(); } } diff --git a/src/features/basicAuth/index.ts b/src/features/basicAuth/index.ts index dd02a3bdc..ae698cba8 100644 --- a/src/features/basicAuth/index.ts +++ b/src/features/basicAuth/index.ts @@ -2,7 +2,7 @@ import { AuthInfo, BrowserWindow, ipcRenderer } from 'electron'; import { state as ModalState } from './store'; -const debug = require('debug')('Ferdium:feature:basicAuth'); +const debug = require('../../preload-safe-debug')('Ferdium:feature:basicAuth'); const state = ModalState; diff --git a/src/features/basicAuth/mainIpcHandler.ts b/src/features/basicAuth/mainIpcHandler.ts index 2f78b1497..5d320df5c 100644 --- a/src/features/basicAuth/mainIpcHandler.ts +++ b/src/features/basicAuth/mainIpcHandler.ts @@ -1,6 +1,6 @@ import { BrowserWindow } from 'electron'; -const debug = require('debug')('Ferdium:feature:basicAuth:main'); +const debug = require('../../preload-safe-debug')('Ferdium:feature:basicAuth:main'); export default function mainIpcHandler(mainWindow: BrowserWindow, authInfo) { debug('Sending basic auth call', authInfo); diff --git a/src/features/basicAuth/store.ts b/src/features/basicAuth/store.ts index 4b71d32fd..e0ae8ba17 100644 --- a/src/features/basicAuth/store.ts +++ b/src/features/basicAuth/store.ts @@ -1,7 +1,7 @@ import { observable } from 'mobx'; import { ipcRenderer } from 'electron'; -const debug = require('debug')('Ferdium:feature:basicAuth'); +const debug = require('../../preload-safe-debug')('Ferdium:feature:basicAuth'); const defaultState = { isModalVisible: true, diff --git a/src/features/communityRecipes/store.ts b/src/features/communityRecipes/store.ts index afd7d0f01..73eaae8b4 100644 --- a/src/features/communityRecipes/store.ts +++ b/src/features/communityRecipes/store.ts @@ -1,8 +1,7 @@ import { computed } from 'mobx'; import { FeatureStore } from '../utils/FeatureStore'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:feature:communityRecipes:store'); +const debug = require('../../preload-safe-debug')('Ferdium:feature:communityRecipes:store'); export class CommunityRecipesStore extends FeatureStore { stores: any; @@ -10,13 +9,13 @@ export class CommunityRecipesStore extends FeatureStore { actions: any; start(stores: any, actions: any) { - console.log('start'); + debug('start'); this.stores = stores; this.actions = actions; } stop() { - console.log('stop'); + debug('stop'); super.stop(); } diff --git a/src/features/publishDebugInfo/Component.js b/src/features/publishDebugInfo/Component.js index 3d4e85dbf..ff052a050 100644 --- a/src/features/publishDebugInfo/Component.js +++ b/src/features/publishDebugInfo/Component.js @@ -14,7 +14,7 @@ import { DEBUG_API } from '../../config'; import AppStore from '../../stores/AppStore'; import ServicesStore from '../../stores/ServicesStore'; -const debug = require('debug')('Ferdium:feature:publishDebugInfo'); +const debug = require('../../preload-safe-debug')('Ferdium:feature:publishDebugInfo'); const messages = defineMessages({ title: { diff --git a/src/features/publishDebugInfo/index.ts b/src/features/publishDebugInfo/index.ts index 33b8eb6f5..597bcdc12 100644 --- a/src/features/publishDebugInfo/index.ts +++ b/src/features/publishDebugInfo/index.ts @@ -3,7 +3,7 @@ import { state as ModalState } from './store'; export { default as Component } from './Component'; const state = ModalState; -const debug = require('debug')('Ferdium:feature:publishDebugInfo'); +const debug = require('../../preload-safe-debug')('Ferdium:feature:publishDebugInfo'); export default function initialize() { debug('Initialize publishDebugInfo feature'); diff --git a/src/features/quickSwitch/index.ts b/src/features/quickSwitch/index.ts index 9d584dc62..9d53d0b2f 100644 --- a/src/features/quickSwitch/index.ts +++ b/src/features/quickSwitch/index.ts @@ -3,7 +3,7 @@ import { state as ModalState } from './store'; export { default as Component } from './Component'; const state = ModalState; -const debug = require('debug')('Ferdium:feature:quickSwitch'); +const debug = require('../../preload-safe-debug')('Ferdium:feature:quickSwitch'); export default function initialize() { debug('Initialize quickSwitch feature'); diff --git a/src/features/serviceProxy/index.ts b/src/features/serviceProxy/index.ts index b3705b190..e0d667a72 100644 --- a/src/features/serviceProxy/index.ts +++ b/src/features/serviceProxy/index.ts @@ -1,8 +1,7 @@ import { autorun, observable } from 'mobx'; import { session } from '@electron/remote'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:feature:serviceProxy'); +const debug = require('../../preload-safe-debug')('Ferdium:feature:serviceProxy'); export const config = observable({ isEnabled: true, @@ -12,7 +11,7 @@ export default function init(stores: { services: { enabled: any }; settings: { proxy: any }; }) { - console.log('Initializing `serviceProxy` feature'); + debug('Initializing `serviceProxy` feature'); autorun(() => { config.isEnabled = true; @@ -20,7 +19,7 @@ export default function init(stores: { const services = stores.services.enabled; const proxySettings = stores.settings.proxy; - console.log('Service Proxy autorun'); + debug('Service Proxy autorun'); for (const service of services) { const s = session.fromPartition(`persist:service-${service.id}`); @@ -36,14 +35,14 @@ export default function init(stores: { const proxyHost = `${serviceProxyConfig.host}${ serviceProxyConfig.port ? `:${serviceProxyConfig.port}` : '' }`; - console.log( + debug( `Setting proxy config from service settings for "${service.name}" (${service.id}) to`, proxyHost, ); s.setProxy({ proxyRules: proxyHost }) .then(() => { - console.log( + debug( `Using proxy "${proxyHost}" for "${service.name}" (${service.id})`, ); }) diff --git a/src/features/todos/preload.ts b/src/features/todos/preload.ts index 4ccee39a0..6c8bc1aea 100644 --- a/src/features/todos/preload.ts +++ b/src/features/todos/preload.ts @@ -1,10 +1,9 @@ import { ipcRenderer } from 'electron'; import { IPC } from './constants'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:feature:todos:preload'); +const debug = require('../../preload-safe-debug')('Ferdium:feature:todos:preload'); -console.log('Preloading Todos Webview'); +debug('Preloading Todos Webview'); let hostMessageListener = ({ action }) => { switch (action) { @@ -28,7 +27,7 @@ window['ferdium'] = { }; ipcRenderer.on(IPC.TODOS_HOST_CHANNEL, (event, message) => { - console.log('Received host message', event, message); + debug('Received host message', event, message); hostMessageListener(message); }); diff --git a/src/features/todos/store.js b/src/features/todos/store.js index 41e632b49..9ece76327 100644 --- a/src/features/todos/store.js +++ b/src/features/todos/store.js @@ -18,8 +18,7 @@ import { createActionBindings } from '../utils/ActionBinding'; import { IPC, TODOS_ROUTES } from './constants'; import UserAgent from '../../models/UserAgent'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:feature:todos:store'); +const debug = require('../../preload-safe-debug')('Ferdium:feature:todos:store'); export default class TodoStore extends FeatureStore { @observable stores = null; @@ -97,7 +96,7 @@ export default class TodoStore extends FeatureStore { // ========== PUBLIC API ========= // @action start(stores, actions) { - console.log('TodoStore::start'); + debug('TodoStore::start'); this.stores = stores; this.actions = actions; @@ -134,7 +133,7 @@ export default class TodoStore extends FeatureStore { @action stop() { super.stop(); - console.log('TodoStore::stop'); + debug('TodoStore::stop'); this.reset(); this.isFeatureActive = false; } @@ -163,7 +162,7 @@ export default class TodoStore extends FeatureStore { }; @action _setTodosWebview = ({ webview }) => { - console.log('_setTodosWebview', webview); + debug('_setTodosWebview', webview); if (this.webview !== webview) { this.webview = webview; this.userAgentModel.setWebviewReference(webview); @@ -171,14 +170,14 @@ export default class TodoStore extends FeatureStore { }; @action _handleHostMessage = message => { - console.log('_handleHostMessage', message); + debug('_handleHostMessage', message); if (message.action === 'todos:create') { this.webview.send(IPC.TODOS_HOST_CHANNEL, message); } }; @action _handleClientMessage = ({ channel, message = {} }) => { - console.log('_handleClientMessage', channel, message); + debug('_handleClientMessage', channel, message); switch (message.action) { case 'todos:initialized': this._onTodosClientInitialized(); @@ -187,7 +186,7 @@ export default class TodoStore extends FeatureStore { this._goToService(message.data); break; default: - console.log('Other message received', channel, message); + debug('Other message received', channel, message); if (this.stores.services.isTodosServiceAdded) { this.actions.service.handleIPCMessage({ serviceId: this.stores.services.isTodosServiceAdded.id, @@ -203,7 +202,7 @@ export default class TodoStore extends FeatureStore { }; @action _toggleTodosFeatureVisibility = () => { - console.log('_toggleTodosFeatureVisibility'); + debug('_toggleTodosFeatureVisibility'); this._updateSettings({ isFeatureEnabledByUser: !this.settings.isFeatureEnabledByUser, @@ -211,14 +210,14 @@ export default class TodoStore extends FeatureStore { }; _openDevTools = () => { - console.log('_openDevTools'); + debug('_openDevTools'); const webview = document.querySelector('#todos-panel webview'); if (webview) webview.openDevTools(); }; _reload = () => { - console.log('_reload'); + debug('_reload'); const webview = document.querySelector('#todos-panel webview'); if (webview) webview.reload(); @@ -286,7 +285,7 @@ export default class TodoStore extends FeatureStore { const { pathname } = this.stores.router.location; if (pathname === TODOS_ROUTES.TARGET) { - console.log('Router is on todos route, show todos panel'); + debug('Router is on todos route, show todos panel'); // todosStore.start(stores, actions); this.stores.router.push('/'); diff --git a/src/features/workspaces/api.ts b/src/features/workspaces/api.ts index 582433527..fb752c565 100644 --- a/src/features/workspaces/api.ts +++ b/src/features/workspaces/api.ts @@ -4,15 +4,14 @@ import Request from '../../stores/lib/Request'; import Workspace from './models/Workspace'; import apiBase from '../../api/apiBase'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:feature:workspaces:api'); +const debug = require('../../preload-safe-debug')('Ferdium:feature:workspaces:api'); export const workspaceApi = { getUserWorkspaces: async () => { const url = `${apiBase()}/workspace`; - console.log('getUserWorkspaces GET', url); + debug('getUserWorkspaces GET', url); const result = await sendAuthRequest(url, { method: 'GET' }); - console.log('getUserWorkspaces RESULT', result); + debug('getUserWorkspaces RESULT', result); if (!result.ok) { throw new Error("Couldn't getUserWorkspaces"); } @@ -26,9 +25,9 @@ export const workspaceApi = { method: 'POST', body: JSON.stringify({ name }), }; - console.log('createWorkspace POST', url, options); + debug('createWorkspace POST', url, options); const result = await sendAuthRequest(url, options); - console.log('createWorkspace RESULT', result); + debug('createWorkspace RESULT', result); if (!result.ok) { throw new Error("Couldn't createWorkspace"); } @@ -37,9 +36,9 @@ export const workspaceApi = { deleteWorkspace: async workspace => { const url = `${apiBase()}/workspace/${workspace.id}`; - console.log('deleteWorkspace DELETE', url); + debug('deleteWorkspace DELETE', url); const result = await sendAuthRequest(url, { method: 'DELETE' }); - console.log('deleteWorkspace RESULT', result); + debug('deleteWorkspace RESULT', result); if (!result.ok) { throw new Error("Couldn't deleteWorkspace"); } @@ -52,9 +51,9 @@ export const workspaceApi = { method: 'PUT', body: JSON.stringify(pick(workspace, ['name', 'services'])), }; - console.log('updateWorkspace UPDATE', url, options); + debug('updateWorkspace UPDATE', url, options); const result = await sendAuthRequest(url, options); - console.log('updateWorkspace RESULT', result); + debug('updateWorkspace RESULT', result); if (!result.ok) { throw new Error("Couldn't updateWorkspace"); } diff --git a/src/features/workspaces/store.js b/src/features/workspaces/store.js index d2ccfeccf..20d32df67 100644 --- a/src/features/workspaces/store.js +++ b/src/features/workspaces/store.js @@ -15,8 +15,7 @@ import { createActionBindings } from '../utils/ActionBinding'; import { KEEP_WS_LOADED_USID } from '../../config'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:feature:workspaces:store'); +const debug = require('../../preload-safe-debug')('Ferdium:feature:workspaces:store'); export default class WorkspacesStore extends FeatureStore { @observable isFeatureActive = false; @@ -70,7 +69,7 @@ export default class WorkspacesStore extends FeatureStore { // ========== PUBLIC API ========= // @action start(stores, actions) { - console.log('WorkspacesStore::start'); + debug('WorkspacesStore::start'); this.stores = stores; this.actions = actions; @@ -116,7 +115,7 @@ export default class WorkspacesStore extends FeatureStore { @action stop() { super.stop(); - console.log('WorkspacesStore::stop'); + debug('WorkspacesStore::stop'); this.reset(); this.isFeatureActive = false; } @@ -274,7 +273,7 @@ export default class WorkspacesStore extends FeatureStore { }; _activateLastUsedWorkspaceReaction = () => { - console.log('_activateLastUsedWorkspaceReaction'); + debug('_activateLastUsedWorkspaceReaction'); if (!this.activeWorkspace && this.userHasWorkspaces) { const { lastActiveWorkspace } = this.settings; if (lastActiveWorkspace) { diff --git a/src/helpers/url-helpers.ts b/src/helpers/url-helpers.ts index abe123577..ddbf4b4f7 100644 --- a/src/helpers/url-helpers.ts +++ b/src/helpers/url-helpers.ts @@ -6,8 +6,7 @@ import { shell } from 'electron'; import { ALLOWED_PROTOCOLS } from '../config'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:Helpers:url'); +const debug = require('../preload-safe-debug')('Ferdium:Helpers:url'); export function isValidExternalURL(url: string | URL) { let parsedUrl: URL; @@ -19,7 +18,7 @@ export function isValidExternalURL(url: string | URL) { const isAllowed = ALLOWED_PROTOCOLS.includes(parsedUrl.protocol); - console.log('protocol check is', isAllowed, 'for:', url); + debug('protocol check is', isAllowed, 'for:', url); return isAllowed; } @@ -38,7 +37,7 @@ export function openExternalUrl( url: string | URL, skipValidityCheck: boolean = false, ) { - console.log('Open url:', url, 'with skipValidityCheck:', skipValidityCheck); + debug('Open url:', url, 'with skipValidityCheck:', skipValidityCheck); if (skipValidityCheck || isValidExternalURL(url)) { shell.openExternal(url.toString()); } diff --git a/src/index.html b/src/index.html index 23fbb6b20..d86e36de9 100644 --- a/src/index.html +++ b/src/index.html @@ -28,6 +28,9 @@ require('./sentry'); const { isDevMode } = require('./environment-remote'); if (isDevMode) { + // Here we must access `debug` directly (instead of through `preload-safe-debug`), + // because we need to set the log level. + // However, this is safe, because we aren't in a preload script. const debugging = require('debug'); debugging.enable(process.env.DEBUG); diff --git a/src/index.ts b/src/index.ts index 6be4f3f18..ef9d5bd72 100644 --- a/src/index.ts +++ b/src/index.ts @@ -12,6 +12,7 @@ import { import { emptyDirSync, ensureFileSync } from 'fs-extra'; import { join } from 'path'; import windowStateKeeper from 'electron-window-state'; +import minimist from 'minimist'; import ms from 'ms'; import { enableWebContents, initializeRemote } from './electron-util'; import { enforceMacOSAppLocation } from './enforce-macos-app-location'; @@ -44,11 +45,10 @@ import { asarPath } from './helpers/asar-helpers'; import { openExternalUrl } from './helpers/url-helpers'; import userAgent from './helpers/userAgent-helpers'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:App'); +const debug = require('./preload-safe-debug')('Ferdium:App'); // Globally set useragent to fix user agent override in service workers -console.log('Set userAgent to', userAgent()); +debug('Set userAgent to ', userAgent()); app.userAgentFallback = userAgent(); // Keep a global reference of the window object, if you don't, the window will @@ -127,7 +127,7 @@ if (!gotTheLock) { if (argv.includes('--reset-window')) { // Needs to be delayed to not interfere with mainWindow.restore(); setTimeout(() => { - console.log('Resetting windows via Task'); + debug('Resetting windows via Task'); window.setPosition( DEFAULT_WINDOW_OPTIONS.x + 100, DEFAULT_WINDOW_OPTIONS.y + 100, @@ -140,7 +140,7 @@ if (!gotTheLock) { } else if (argv.includes('--quit')) { // Needs to be delayed to not interfere with mainWindow.restore(); setTimeout(() => { - console.log('Quitting Ferdium via Task'); + debug('Quitting Ferdium via Task'); app.quit(); }, 1); } @@ -162,7 +162,7 @@ if ( // Disable GPU acceleration if (!retrieveSettingValue('enableGPUAcceleration', false)) { - console.log('Disable GPU Acceleration'); + debug('Disable GPU Acceleration'); app.disableHardwareAcceleration(); } @@ -184,7 +184,7 @@ const createWindow = () => { let posY = mainWindowState.y || DEFAULT_WINDOW_OPTIONS.y; if (!isPositionValid({ x: posX, y: posY })) { - console.log('Window is out of screen bounds, resetting window'); + debug('Window is out of screen bounds, resetting window'); posX = DEFAULT_WINDOW_OPTIONS.x; posY = DEFAULT_WINDOW_OPTIONS.y; } @@ -285,7 +285,7 @@ const createWindow = () => { // Emitted when the window is closed. mainWindow.on('close', e => { - console.log('Window: close window'); + debug('Window: close window'); // Dereference the window object, usually you would store windows // in an array if your app supports multi windows, this is the time // when you should delete the corresponding element. @@ -298,7 +298,7 @@ const createWindow = () => { ) { e.preventDefault(); if (isWindows) { - console.log('Window: minimize'); + debug('Window: minimize'); mainWindow?.minimize(); if ( @@ -307,16 +307,16 @@ const createWindow = () => { DEFAULT_APP_SETTINGS.closeToSystemTray, ) ) { - console.log('Skip taskbar: true'); + debug('Skip taskbar: true'); mainWindow?.setSkipTaskbar(true); } } else if (isMac && mainWindow?.isFullScreen()) { - console.log('Window: leaveFullScreen and hide'); + debug('Window: leaveFullScreen and hide'); mainWindow.once('show', () => mainWindow?.setFullScreen(true)); mainWindow.once('leave-full-screen', () => mainWindow?.hide()); mainWindow.setFullScreen(false); } else { - console.log('Window: hide'); + debug('Window: hide'); mainWindow?.hide(); } } else { @@ -337,31 +337,31 @@ const createWindow = () => { DEFAULT_APP_SETTINGS.minimizeToSystemTray, ) ) { - console.log('Skip taskbar: true'); + debug('Skip taskbar: true'); mainWindow?.setSkipTaskbar(true); trayIcon.show(); } }); mainWindow.on('maximize', () => { - console.log('Window: maximize'); + debug('Window: maximize'); // @ts-expect-error Property 'isMaximized' does not exist on type 'App'. app.isMaximized = true; }); mainWindow.on('unmaximize', () => { - console.log('Window: unmaximize'); + debug('Window: unmaximize'); // @ts-expect-error Property 'isMaximized' does not exist on type 'App'. app.isMaximized = false; }); mainWindow.on('restore', () => { - console.log('Window: restore'); + debug('Window: restore'); mainWindow?.setSkipTaskbar(false); // @ts-expect-error Property 'wasMaximized' does not exist on type 'App'. if (app.wasMaximized) { - console.log('Window: was maximized before, maximize window'); + debug('Window: was maximized before, maximize window'); mainWindow?.maximize(); } @@ -371,7 +371,7 @@ const createWindow = () => { DEFAULT_APP_SETTINGS.enableSystemTray, ) ) { - console.log('Tray: hiding tray icon'); + debug('Tray: hiding tray icon'); trayIcon.hide(); } }); @@ -383,7 +383,7 @@ const createWindow = () => { } mainWindow.on('show', () => { - console.log('Skip taskbar: true'); + debug('Skip taskbar: true'); mainWindow?.setSkipTaskbar(false); }); @@ -423,7 +423,7 @@ const createWindow = () => { // used for Kerberos support // Usage e.g. MACOS // $ Ferdium.app/Contents/MacOS/Ferdium --auth-server-whitelist *.mydomain.com --auth-negotiate-delegate-whitelist *.mydomain.com -const argv = require('minimist')(process.argv.slice(1)); +const argv = minimist(process.argv.slice(1)); if (argv['auth-server-whitelist']) { app.commandLine.appendSwitch( @@ -500,18 +500,18 @@ let authCallback = noop; app.on('login', (event, _webContents, _request, authInfo, callback) => { // @ts-expect-error Type '(username?: string | undefined, password?: string | undefined) => void' is not assignable to type '() => null'. authCallback = callback; - console.log('browser login event', authInfo); + debug('browser login event', authInfo); event.preventDefault(); if (!authInfo.isProxy && authInfo.scheme === 'basic') { - console.log('basic auth handler', authInfo); + debug('basic auth handler', authInfo); basicAuthHandler(mainWindow!, authInfo); } }); // TODO: evaluate if we need to store the authCallback for every service ipcMain.on('feature-basic-auth-credentials', (_e, { user, password }) => { - console.log('Received basic auth credentials', user, '********'); + debug('Received basic auth credentials', user, '********'); // @ts-expect-error Expected 0 arguments, but got 2. authCallback(user, password); @@ -530,13 +530,13 @@ ipcMain.on('open-browser-window', (_e, { url, serviceId }) => { enableWebContents(child.webContents); child.show(); child.loadURL(url); - console.log('Received open-browser-window', url); + debug('Received open-browser-window', url); }); ipcMain.on( 'modifyRequestHeaders', (_e, { modifiedRequestHeaders, serviceId }) => { - console.log( + debug( `Received modifyRequestHeaders ${modifiedRequestHeaders} for serviceId ${serviceId}`, ); for (const headerFilterSet of modifiedRequestHeaders) { @@ -557,7 +557,7 @@ ipcMain.on( ); ipcMain.on('knownCertificateHosts', (_e, { knownHosts, serviceId }) => { - console.log( + debug( `Received knownCertificateHosts ${knownHosts} for serviceId ${serviceId}`, ); session @@ -577,7 +577,7 @@ ipcMain.on('knownCertificateHosts', (_e, { knownHosts, serviceId }) => { }); ipcMain.on('feature-basic-auth-cancel', () => { - console.log('Cancel basic auth'); + debug('Cancel basic auth'); // @ts-expect-error Expected 0 arguments, but got 2. authCallback(null); @@ -596,7 +596,7 @@ ipcMain.on('find-in-page', (e, text, options) => { } } const requestId = webContents.findInPage(text, sanitizedOptions); - console.log('Find in page', text, options, requestId); + debug('Find in page', text, options, requestId); e.returnValue = requestId; } else { e.returnValue = null; @@ -625,10 +625,10 @@ ipcMain.on('set-spellchecker-locales', (_e, { locale, serviceId }) => { const serviceSession = session.fromPartition(`persist:service-${serviceId}`); const [defaultLocale] = serviceSession.getSpellCheckerLanguages(); - console.log(`Spellchecker default locale is: ${defaultLocale}`); + debug(`Spellchecker default locale is: ${defaultLocale}`); const locales = [locale, defaultLocale, DEFAULT_APP_SETTINGS.fallbackLocale]; - console.log(`Setting spellchecker locales to: ${locales}`); + debug(`Setting spellchecker locales to: ${locales}`); serviceSession.setSpellCheckerLanguages(locales); }); @@ -646,10 +646,10 @@ app.on('window-all-closed', () => { DEFAULT_APP_SETTINGS.runInBackground, ) ) { - console.log('Window: all windows closed, quit app'); + debug('Window: all windows closed, quit app'); app.quit(); } else { - console.log("Window: don't quit app"); + debug("Window: don't quit app"); } }); @@ -695,7 +695,7 @@ app.on('will-finish-launching', () => { event.preventDefault(); onDidLoad((window: BrowserWindow) => { - console.log('open-url event', url); + debug('open-url event', url); handleDeepLink(window, url); }); }); diff --git a/src/internal-server/app/Controllers/Http/RecipeController.js b/src/internal-server/app/Controllers/Http/RecipeController.js index 474ffadb4..5f7c32d70 100644 --- a/src/internal-server/app/Controllers/Http/RecipeController.js +++ b/src/internal-server/app/Controllers/Http/RecipeController.js @@ -4,7 +4,7 @@ const { validateAll } = use('Validator'); const Env = use('Env'); const fetch = require('node-fetch'); -const debug = require('debug')('Ferdium:internalServer:RecipeController'); +const debug = require('../../../../preload-safe-debug')('Ferdium:internalServer:RecipeController'); const { LIVE_FERDIUM_API } = require('../../../../config'); const { API_VERSION } = require('../../../../environment-remote'); diff --git a/src/models/Service.js b/src/models/Service.js index 9f345375f..1fca034bc 100644 --- a/src/models/Service.js +++ b/src/models/Service.js @@ -14,8 +14,7 @@ import { ifUndefinedNumber, } from '../jsUtils'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:Service'); +const debug = require('../preload-safe-debug')('Ferdium:Service'); export default class Service { id = ''; @@ -306,25 +305,25 @@ export default class Service { // Send those headers to ipcMain so that it can be set in session if (typeof this.recipe.modifyRequestHeaders === 'function') { const modifiedRequestHeaders = this.recipe.modifyRequestHeaders(); - console.log(this.name, 'modifiedRequestHeaders', modifiedRequestHeaders); + debug(this.name, 'modifiedRequestHeaders', modifiedRequestHeaders); ipcRenderer.send('modifyRequestHeaders', { modifiedRequestHeaders, serviceId: this.id, }); } else { - console.log(this.name, 'modifyRequestHeaders is not defined in the recipe'); + debug(this.name, 'modifyRequestHeaders is not defined in the recipe'); } // if the recipe has implemented 'knownCertificateHosts' if (typeof this.recipe.knownCertificateHosts === 'function') { const knownHosts = this.recipe.knownCertificateHosts(); - console.log(this.name, 'knownCertificateHosts', knownHosts); + debug(this.name, 'knownCertificateHosts', knownHosts); ipcRenderer.send('knownCertificateHosts', { knownHosts, serviceId: this.id, }); } else { - console.log(this.name, 'knownCertificateHosts is not defined in the recipe'); + debug(this.name, 'knownCertificateHosts is not defined in the recipe'); } this.webview.addEventListener('ipc-message', async e => { @@ -348,7 +347,7 @@ export default class Service { this.webview.addEventListener( 'new-window', (event, url, frameName, options) => { - console.log('new-window', event, url, frameName, options); + debug('new-window', event, url, frameName, options); if (!isValidExternalURL(event.url)) { return; } @@ -372,7 +371,7 @@ export default class Service { ); this.webview.addEventListener('did-start-loading', event => { - console.log('Did start load', this.name, event); + debug('Did start load', this.name, event); this.hasCrashed = false; this.isLoading = true; @@ -391,7 +390,7 @@ export default class Service { this.webview.addEventListener('did-navigate', didLoad.bind(this)); this.webview.addEventListener('did-fail-load', event => { - console.log('Service failed to load', this.name, event); + debug('Service failed to load', this.name, event); if ( event.isMainFrame && event.errorCode !== -21 && @@ -404,33 +403,33 @@ export default class Service { }); this.webview.addEventListener('crashed', () => { - console.log('Service crashed', this.name); + debug('Service crashed', this.name); this.hasCrashed = true; }); this.webview.addEventListener('found-in-page', ({ result }) => { - console.log('Found in page', result); + debug('Found in page', result); this.webview.send('found-in-page', result); }); webviewWebContents.on('login', (event, request, authInfo, callback) => { // const authCallback = callback; - console.log('browser login event', authInfo); + debug('browser login event', authInfo); event.preventDefault(); if (authInfo.isProxy && authInfo.scheme === 'basic') { - console.log('Sending service echo ping'); + debug('Sending service echo ping'); webviewWebContents.send('get-service-id'); - console.log('Received service id', this.id); + debug('Received service id', this.id); const ps = stores.settings.proxy[this.id]; if (ps) { - console.log('Sending proxy auth callback for service', this.id); + debug('Sending proxy auth callback for service', this.id); callback(ps.user, ps.password); } else { - console.log('No proxy auth config found for', this.id); + debug('No proxy auth config found for', this.id); } } }); diff --git a/src/models/UserAgent.js b/src/models/UserAgent.js index f818ee9d0..3e1394b45 100644 --- a/src/models/UserAgent.js +++ b/src/models/UserAgent.js @@ -2,8 +2,7 @@ import { action, computed, observe, observable } from 'mobx'; import defaultUserAgent from '../helpers/userAgent-helpers'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:UserAgent'); +const debug = require('../preload-safe-debug')('Ferdium:UserAgent'); export default class UserAgent { _willNavigateListener = null; @@ -79,7 +78,7 @@ export default class UserAgent { @action _handleNavigate(url, forwardingHack = false) { if (url.startsWith('https://accounts.google.com')) { if (!this.chromelessUserAgent) { - console.log('Setting user agent to chromeless for url', url); + debug('Setting user agent to chromeless for url', url); this.chromelessUserAgent = true; this.webview.userAgent = this.userAgent; if (forwardingHack) { @@ -87,14 +86,14 @@ export default class UserAgent { } } } else if (this.chromelessUserAgent) { - console.log('Setting user agent to contain chrome for url', url); + debug('Setting user agent to contain chrome for url', url); this.chromelessUserAgent = false; this.webview.userAgent = this.userAgent; } } _addWebviewEvents(webview) { - console.log('Adding event handlers'); + debug('Adding event handlers'); this._willNavigateListener = event => this._handleNavigate(event.url, true); webview.addEventListener('will-navigate', this._willNavigateListener); @@ -104,7 +103,7 @@ export default class UserAgent { } _removeWebviewEvents(webview) { - console.log('Removing event handlers'); + debug('Removing event handlers'); webview.removeEventListener('will-navigate', this._willNavigateListener); webview.removeEventListener('did-navigate', this._didNavigateListener); diff --git a/src/preload-safe-debug.ts b/src/preload-safe-debug.ts new file mode 100644 index 000000000..d96ea9017 --- /dev/null +++ b/src/preload-safe-debug.ts @@ -0,0 +1,29 @@ +/* + eslint-disable global-require -- + This file contains a workaround for situations were global require is problematic. +*/ + +/** + * Make sure we don't try to load `debug` in the preload script. + * + * Doing so would trigger the bug https://github.com/electron/electron/issues/31689 + * because `debug` will try to access `localStorage` to save the log level: + * https://www.npmjs.com/package/debug#user-content-browser-support + * + * We check for the presence of `ipcRenderer`, a render-only electron API, + * to detect whether we're in the renderer process. + * We serve the user interface from the `file://` origin, so any different origin + * must be a preload script. + */ +module.exports = function debug(namespace: string): (...params: any[]) => void { + if ('ipcRenderer' in require('electron') && window.origin !== 'file://') { + // Only output debug messages to the console if debugging is requested. + // We don't reimplement the matching algorithm from `debug` and just dump all + // messages to the console if some form of `Ferdium` debugging is enabled. + if (process.env.DEBUG?.startsWith('Ferdium:')) { + return (...params) => console.debug(`[${namespace}]`, ...params); + } + return () => { }; + } + return require('debug')(namespace); +} 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, diff --git a/src/webview/badge.ts b/src/webview/badge.ts index 0ff1ecaf6..898f8cdcf 100644 --- a/src/webview/badge.ts +++ b/src/webview/badge.ts @@ -1,7 +1,6 @@ import { ipcRenderer } from 'electron'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:Plugin:BadgeHandler'); +const debug = require('../preload-safe-debug')('Ferdium:Plugin:BadgeHandler'); export class BadgeHandler { // TODO: Need to extract this into a utility class and reuse outside of the recipes @@ -27,7 +26,7 @@ export class BadgeHandler { indirect: this.safeParseInt(indirect), }; - console.log('Sending badge count to host: %j', count); + debug('Sending badge count to host: %j', count); ipcRenderer.sendToHost('message-counts', count); } } diff --git a/src/webview/darkmode.ts b/src/webview/darkmode.ts index 99ee68757..34f987b51 100644 --- a/src/webview/darkmode.ts +++ b/src/webview/darkmode.ts @@ -1,8 +1,7 @@ import { join } from 'path'; import { pathExistsSync, readFileSync } from 'fs-extra'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:DarkMode'); +const debug = require('../preload-safe-debug')('Ferdium:DarkMode'); const chars = [...'abcdefghijklmnopqrstuvwxyz']; @@ -27,7 +26,7 @@ export function injectDarkModeStyle(recipePath: string) { document.querySelector('head')?.appendChild(styles); - console.log('Injected Dark Mode style with ID', ID); + debug('Injected Dark Mode style with ID', ID); } } @@ -37,7 +36,7 @@ export function removeDarkModeStyle() { if (style) { style.remove(); - console.log('Removed Dark Mode Style with ID', ID); + debug('Removed Dark Mode Style with ID', ID); } } diff --git a/src/webview/dialogTitle.ts b/src/webview/dialogTitle.ts index a5bcb4c41..12e007e26 100644 --- a/src/webview/dialogTitle.ts +++ b/src/webview/dialogTitle.ts @@ -1,7 +1,6 @@ import { ipcRenderer } from 'electron'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:Plugin:DialogTitleHandler'); +const debug = require('../preload-safe-debug')('Ferdium:Plugin:DialogTitleHandler'); export class DialogTitleHandler { titleCache: { title: string }; @@ -26,7 +25,7 @@ export class DialogTitleHandler { return; } - console.log('Sending active dialog title to host %s', newTitle); + debug('Sending active dialog title to host %s', newTitle); ipcRenderer.sendToHost('active-dialog-title', newTitle); this.titleCache.title = newTitle; diff --git a/src/webview/lib/RecipeWebview.ts b/src/webview/lib/RecipeWebview.ts index cf70164ef..e7a39579b 100644 --- a/src/webview/lib/RecipeWebview.ts +++ b/src/webview/lib/RecipeWebview.ts @@ -2,8 +2,7 @@ import { ipcRenderer } from 'electron'; import { BrowserWindow } from '@electron/remote'; import { pathExistsSync, readFileSync, existsSync } from 'fs-extra'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:Plugin:RecipeWebview'); +const debug = require('../../preload-safe-debug')('Ferdium:Plugin:RecipeWebview'); class RecipeWebview { badgeHandler: any; @@ -28,7 +27,7 @@ class RecipeWebview { ipcRenderer.on('poll', () => { this.loopFunc(); - console.log('Poll event'); + debug('Poll event'); // This event is for checking if the service recipe is still actively // communicating with the client @@ -110,7 +109,7 @@ class RecipeWebview { if (head) { head.append(styles); - console.log('Append styles', styles); + debug('Append styles', styles); } } }); @@ -122,13 +121,13 @@ class RecipeWebview { if (existsSync(file)) { return readFileSync(file, 'utf8'); } - console.log('Script not found', file); + debug('Script not found', file); return null; }), ).then(scripts => { const scriptsFound = scripts.filter(script => script !== null); if (scriptsFound.length > 0) { - console.log('Inject scripts to main world', scriptsFound); + debug('Inject scripts to main world', scriptsFound); ipcRenderer.sendToHost('inject-js-unsafe', ...scriptsFound); } }); diff --git a/src/webview/notifications.ts b/src/webview/notifications.ts index ff9c844d0..8b2831754 100644 --- a/src/webview/notifications.ts +++ b/src/webview/notifications.ts @@ -2,8 +2,7 @@ import { ipcRenderer } from 'electron'; import { v1 as uuidV1 } from 'uuid'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:Notifications'); +const debug = require('../preload-safe-debug')('Ferdium:Notifications'); export class NotificationsHandler { onNotify = (data: { title: string; options: any; notificationId: string }) => @@ -11,7 +10,7 @@ export class NotificationsHandler { displayNotification(title: string, options: any) { return new Promise(resolve => { - console.log('New notification', title, options); + debug('New notification', title, options); const notificationId = uuidV1(); diff --git a/src/webview/recipe.js b/src/webview/recipe.js index 1f3017ccd..eff20c2d3 100644 --- a/src/webview/recipe.js +++ b/src/webview/recipe.js @@ -50,8 +50,7 @@ import { import { DEFAULT_APP_SETTINGS } from '../config'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:Plugin'); +const debug = require('../preload-safe-debug')('Ferdium:Plugin'); const badgeHandler = new BadgeHandler(); @@ -65,7 +64,7 @@ const notificationsHandler = new NotificationsHandler(); const originalWindowOpen = window.open; window.open = (url, frameName, features) => { - console.log('window.open', url, frameName, features); + debug('window.open', url, frameName, features); if (!url) { // The service hasn't yet supplied a URL (as used in Skype). // Return a new dummy window object and wait for the service to change the properties @@ -171,12 +170,12 @@ class RecipeController { async initialize() { for (const channel of Object.keys(this.ipcEvents)) { ipcRenderer.on(channel, (...args) => { - console.log('Received IPC event for channel', channel, 'with', ...args); + debug('Received IPC event for channel', channel, 'with', ...args); this[this.ipcEvents[channel]](...args); }); } - console.log('Send "hello" to host'); + debug('Send "hello" to host'); setTimeout(() => ipcRenderer.sendToHost('hello'), 100); this.spellcheckingProvider = null; @@ -199,9 +198,9 @@ class RecipeController { } loadRecipeModule(event, config, recipe) { - console.log('loadRecipeModule'); + debug('loadRecipeModule'); const modulePath = join(recipe.path, 'webview.js'); - console.log('module path', modulePath); + debug('module path', modulePath); // Delete module from cache delete require.cache[require.resolve(modulePath)]; try { @@ -214,7 +213,7 @@ class RecipeController { if (existsSync(modulePath)) { // eslint-disable-next-line import/no-dynamic-require require(modulePath)(this.recipe, { ...config, recipe }); - console.log('Initialize Recipe', config, recipe); + debug('Initialize Recipe', config, recipe); } this.settings.service = Object.assign(config, { recipe }); @@ -266,18 +265,18 @@ class RecipeController { } update() { - console.log('enableSpellchecking', this.settings.app.enableSpellchecking); - console.log('isDarkModeEnabled', this.settings.service.isDarkModeEnabled); - console.log( + debug('enableSpellchecking', this.settings.app.enableSpellchecking); + debug('isDarkModeEnabled', this.settings.service.isDarkModeEnabled); + debug( 'System spellcheckerLanguage', this.settings.app.spellcheckerLanguage, ); - console.log( + debug( 'Service spellcheckerLanguage', this.settings.service.spellcheckerLanguage, ); - console.log('darkReaderSettigs', this.settings.service.darkReaderSettings); - console.log('searchEngine', this.settings.app.searchEngine); + debug('darkReaderSettigs', this.settings.service.darkReaderSettings); + debug('searchEngine', this.settings.app.searchEngine); if (this.userscript && this.userscript.internal_setSettings) { this.userscript.internal_setSettings(this.settings); @@ -285,10 +284,10 @@ class RecipeController { if (this.settings.app.enableSpellchecking) { let { spellcheckerLanguage } = this; - console.log(`Setting spellchecker language to ${spellcheckerLanguage}`); + debug(`Setting spellchecker language to ${spellcheckerLanguage}`); if (spellcheckerLanguage.includes('automatic')) { this.automaticLanguageDetection(); - console.log( + debug( 'Found `automatic` locale, falling back to user locale until detected', this.settings.app.locale, ); @@ -296,14 +295,14 @@ class RecipeController { } switchDict(spellcheckerLanguage, this.settings.service.id); } else { - console.log('Disable spellchecker'); + debug('Disable spellchecker'); } if (!this.recipe) { this.hasUpdatedBeforeRecipeLoaded = true; } - console.log( + debug( 'Darkmode enabled?', this.settings.service.isDarkModeEnabled, 'Dark theme active?', @@ -323,11 +322,11 @@ class RecipeController { this.settings.service.isDarkModeEnabled && this.settings.app.isDarkThemeActive !== false ) { - console.log('Enable dark mode'); + debug('Enable dark mode'); // Check if recipe has a custom dark mode handler if (this.recipe && this.recipe.darkModeHandler) { - console.log('Using custom dark mode handler'); + debug('Using custom dark mode handler'); // Remove other dark mode styles if they were already loaded if (this.hasUpdatedBeforeRecipeLoaded) { @@ -338,7 +337,7 @@ class RecipeController { this.recipe.darkModeHandler(true, handlerConfig); } else if (darkModeStyleExists(this.settings.service.recipe.path)) { - console.log('Injecting darkmode from recipe'); + debug('Injecting darkmode from recipe'); injectDarkModeStyle(this.settings.service.recipe.path); // Make sure universal dark mode is disabled @@ -348,7 +347,7 @@ class RecipeController { this.settings.app.universalDarkMode && !ignoreList.includes(window.location.host) ) { - console.log('Injecting Dark Reader'); + debug('Injecting Dark Reader'); // Use Dark Reader instead const { brightness, contrast, sepia } = @@ -362,8 +361,8 @@ class RecipeController { this.universalDarkModeInjected = true; } } else { - console.log('Remove dark mode'); - console.log('DarkMode disabled - removing remaining styles'); + debug('Remove dark mode'); + debug('DarkMode disabled - removing remaining styles'); if (this.recipe && this.recipe.darkModeHandler) { // Remove other dark mode styles if they were already loaded @@ -375,10 +374,10 @@ class RecipeController { this.recipe.darkModeHandler(false, handlerConfig); } else if (isDarkModeStyleInjected()) { - console.log('Removing injected darkmode from recipe'); + debug('Removing injected darkmode from recipe'); removeDarkModeStyle(); } else { - console.log('Removing Dark Reader'); + debug('Removing Dark Reader'); disableDarkMode(); this.universalDarkModeInjected = false; @@ -406,7 +405,7 @@ class RecipeController { } serviceIdEcho(event) { - console.log('Received a service echo ping'); + debug('Received a service echo ping'); event.sender.send('service-id', this.settings.service.id); } @@ -428,7 +427,7 @@ class RecipeController { // Force a minimum length to get better detection results if (value.length < 25) return; - console.log('Detecting language for', value); + debug('Detecting language for', value); const locale = await ipcRenderer.invoke('detect-language', { sample: value, }); @@ -438,7 +437,7 @@ class RecipeController { const spellcheckerLocale = getSpellcheckerLocaleByFuzzyIdentifier(locale); - console.log( + debug( 'Language detected reliably, setting spellchecker language to', spellcheckerLocale, ); diff --git a/src/webview/sessionHandler.ts b/src/webview/sessionHandler.ts index a2906113d..00eacdf50 100644 --- a/src/webview/sessionHandler.ts +++ b/src/webview/sessionHandler.ts @@ -1,5 +1,4 @@ -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:Plugin:SessionHandler'); +const debug = require('../preload-safe-debug')('Ferdium:Plugin:SessionHandler'); export class SessionHandler { async releaseServiceWorkers() { @@ -8,10 +7,10 @@ export class SessionHandler { await window.navigator.serviceWorker.getRegistrations(); for (const registration of registrations) { registration.unregister(); - console.log('ServiceWorker unregistered'); + debug('ServiceWorker unregistered'); } } catch (error) { - console.log(error); + debug(error); } } } diff --git a/src/webview/spellchecker.ts b/src/webview/spellchecker.ts index 8cf16a7ba..8e452c791 100644 --- a/src/webview/spellchecker.ts +++ b/src/webview/spellchecker.ts @@ -2,8 +2,7 @@ import { ipcRenderer } from 'electron'; import { SPELLCHECKER_LOCALES } from '../i18n/languages'; import { isMac } from '../environment'; -// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed -// const debug = require('debug')('Ferdium:spellchecker'); +const debug = require('../preload-safe-debug')('Ferdium:spellchecker'); export function getSpellcheckerLocaleByFuzzyIdentifier(identifier: string) { const locales = Object.keys(SPELLCHECKER_LOCALES).filter( @@ -17,14 +16,14 @@ export function getSpellcheckerLocaleByFuzzyIdentifier(identifier: string) { export function switchDict(fuzzyLocale: string, serviceId: string) { if (isMac) { - console.log('Ignoring dictionary changes on macOS'); + debug('Ignoring dictionary changes on macOS'); return; } - console.log(`Setting spellchecker locale from: ${fuzzyLocale}`); + debug(`Setting spellchecker locale from: ${fuzzyLocale}`); const locale = getSpellcheckerLocaleByFuzzyIdentifier(fuzzyLocale); if (locale) { - console.log(`Sending spellcheck locales to host: ${locale}`); + debug(`Sending spellcheck locales to host: ${locale}`); ipcRenderer.send('set-spellchecker-locales', { locale, serviceId }); } } -- cgit v1.2.3-54-g00ecf