aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--CONTRIBUTING.md2
-rw-r--r--src/api/server/LocalApi.ts9
-rw-r--r--src/api/server/ServerApi.ts61
-rw-r--r--src/components/services/content/ServiceWebview.js9
-rw-r--r--src/components/settings/settings/EditSettingsForm.js2
-rw-r--r--src/containers/settings/EditSettingsScreen.js2
-rw-r--r--src/electron/Settings.ts2
-rw-r--r--src/electron/ipc-api/autoUpdate.ts2
-rw-r--r--src/electron/ipc-api/cld.ts2
-rw-r--r--src/electron/ipc-api/dnd.ts2
-rw-r--r--src/electron/ipc-api/download.ts7
-rw-r--r--src/electron/ipc-api/sessionStorage.ts9
-rw-r--r--src/electron/macOSPermissions.ts19
-rw-r--r--src/features/basicAuth/index.ts2
-rw-r--r--src/features/basicAuth/mainIpcHandler.ts2
-rw-r--r--src/features/basicAuth/store.ts2
-rw-r--r--src/features/communityRecipes/store.ts7
-rw-r--r--src/features/publishDebugInfo/Component.js2
-rw-r--r--src/features/publishDebugInfo/index.ts2
-rw-r--r--src/features/quickSwitch/index.ts2
-rw-r--r--src/features/serviceProxy/index.ts11
-rw-r--r--src/features/todos/preload.ts7
-rw-r--r--src/features/todos/store.js23
-rw-r--r--src/features/workspaces/api.ts19
-rw-r--r--src/features/workspaces/store.js9
-rw-r--r--src/helpers/url-helpers.ts7
-rw-r--r--src/index.html3
-rw-r--r--src/index.ts66
-rw-r--r--src/internal-server/app/Controllers/Http/RecipeController.js2
-rw-r--r--src/models/Service.js31
-rw-r--r--src/models/UserAgent.js11
-rw-r--r--src/preload-safe-debug.ts29
-rw-r--r--src/stores/AppStore.js37
-rw-r--r--src/stores/RecipesStore.js11
-rw-r--r--src/stores/RequestStore.js5
-rw-r--r--src/stores/ServicesStore.js55
-rw-r--r--src/stores/SettingsStore.js11
-rw-r--r--src/stores/UserStore.js5
-rw-r--r--src/webview/badge.ts5
-rw-r--r--src/webview/darkmode.ts7
-rw-r--r--src/webview/dialogTitle.ts5
-rw-r--r--src/webview/lib/RecipeWebview.ts11
-rw-r--r--src/webview/notifications.ts5
-rw-r--r--src/webview/recipe.js57
-rw-r--r--src/webview/sessionHandler.ts7
-rw-r--r--src/webview/spellchecker.ts9
46 files changed, 300 insertions, 295 deletions
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
202``` 202```
203 203
204Note: please prefer [`debug()`](https://github.com/visionmedia/debug) over `console.log()`. 204Note: please prefer [`debug()`](https://github.com/visionmedia/debug) over `console.log()`.
205However, 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.
206Please use the `src/preload-safe-debug` module instead until the bug gets fixed.
205 207
206### Styleguide 208### Styleguide
207 209
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';
4 4
5import { getServicePartitionsDirectory } from '../../helpers/service-helpers'; 5import { getServicePartitionsDirectory } from '../../helpers/service-helpers';
6 6
7// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 7const debug = require('../../preload-safe-debug')('Ferdium:LocalApi');
8// const debug = require('debug')('Ferdium:LocalApi');
9 8
10export default class LocalApi { 9export default class LocalApi {
11 // Settings 10 // Settings
12 getAppSettings(type: string) { 11 getAppSettings(type: string) {
13 return new Promise(resolve => { 12 return new Promise(resolve => {
14 ipcRenderer.once('appSettings', (_event, resp) => { 13 ipcRenderer.once('appSettings', (_event, resp) => {
15 console.log('LocalApi::getAppSettings resolves', resp.type, resp.data); 14 debug('LocalApi::getAppSettings resolves', resp.type, resp.data);
16 resolve(resp); 15 resolve(resp);
17 }); 16 });
18 17
@@ -21,7 +20,7 @@ export default class LocalApi {
21 } 20 }
22 21
23 async updateAppSettings(type: string, data: any) { 22 async updateAppSettings(type: string, data: any) {
24 console.log('LocalApi::updateAppSettings resolves', type, data); 23 debug('LocalApi::updateAppSettings resolves', type, data);
25 ipcRenderer.send('updateAppSettings', { 24 ipcRenderer.send('updateAppSettings', {
26 type, 25 type,
27 data, 26 data,
@@ -40,7 +39,7 @@ export default class LocalApi {
40 reject(err); 39 reject(err);
41 } 40 }
42 41
43 console.log('LocalApi::getAppCacheSize resolves', bytes); 42 debug('LocalApi::getAppCacheSize resolves', bytes);
44 resolve(bytes); 43 resolve(bytes);
45 }, 44 },
46 ); 45 );
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 {
35 35
36import { removeServicePartitionDirectory } from '../../helpers/service-helpers'; 36import { removeServicePartitionDirectory } from '../../helpers/service-helpers';
37 37
38// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 38const debug = require('../../preload-safe-debug')('Ferdium:ServerApi');
39// const debug = require('debug')('Ferdium:ServerApi');
40 39
41module.paths.unshift(getDevRecipeDirectory(), getRecipeDirectory()); 40module.paths.unshift(getDevRecipeDirectory(), getRecipeDirectory());
42 41
@@ -62,7 +61,7 @@ export default class ServerApi {
62 } 61 }
63 const u = await request.json(); 62 const u = await request.json();
64 63
65 console.log('ServerApi::login resolves', u); 64 debug('ServerApi::login resolves', u);
66 return u.token; 65 return u.token;
67 } 66 }
68 67
@@ -80,7 +79,7 @@ export default class ServerApi {
80 } 79 }
81 const u = await request.json(); 80 const u = await request.json();
82 81
83 console.log('ServerApi::signup resolves', u); 82 debug('ServerApi::signup resolves', u);
84 return u.token; 83 return u.token;
85 } 84 }
86 85
@@ -93,7 +92,7 @@ export default class ServerApi {
93 throw new Error(request.statusText); 92 throw new Error(request.statusText);
94 } 93 }
95 94
96 console.log('ServerApi::inviteUser'); 95 debug('ServerApi::inviteUser');
97 return true; 96 return true;
98 } 97 }
99 98
@@ -113,7 +112,7 @@ export default class ServerApi {
113 } 112 }
114 const r = await request.json(); 113 const r = await request.json();
115 114
116 console.log('ServerApi::retrievePassword'); 115 debug('ServerApi::retrievePassword');
117 return r; 116 return r;
118 } 117 }
119 118
@@ -129,7 +128,7 @@ export default class ServerApi {
129 const data = await request.json(); 128 const data = await request.json();
130 129
131 const user = new UserModel(data); 130 const user = new UserModel(data);
132 console.log('ServerApi::userInfo resolves', user); 131 debug('ServerApi::userInfo resolves', user);
133 132
134 return user; 133 return user;
135 } 134 }
@@ -147,7 +146,7 @@ export default class ServerApi {
147 const user = Object.assign(updatedData, { 146 const user = Object.assign(updatedData, {
148 data: new UserModel(updatedData.data), 147 data: new UserModel(updatedData.data),
149 }); 148 });
150 console.log('ServerApi::updateUserInfo resolves', user); 149 debug('ServerApi::updateUserInfo resolves', user);
151 return user; 150 return user;
152 } 151 }
153 152
@@ -160,7 +159,7 @@ export default class ServerApi {
160 } 159 }
161 const data = await request.json(); 160 const data = await request.json();
162 161
163 console.log('ServerApi::deleteAccount resolves', data); 162 debug('ServerApi::deleteAccount resolves', data);
164 return data; 163 return data;
165 } 164 }
166 165
@@ -178,7 +177,7 @@ export default class ServerApi {
178 177
179 const services = await this._mapServiceModels(data); 178 const services = await this._mapServiceModels(data);
180 const filteredServices = services.filter(service => !!service); 179 const filteredServices = services.filter(service => !!service);
181 console.log('ServerApi::getServices resolves', filteredServices); 180 debug('ServerApi::getServices resolves', filteredServices);
182 return filteredServices; 181 return filteredServices;
183 } 182 }
184 183
@@ -205,7 +204,7 @@ export default class ServerApi {
205 data: await this._prepareServiceModel(serviceData.data), 204 data: await this._prepareServiceModel(serviceData.data),
206 }); 205 });
207 206
208 console.log('ServerApi::createService resolves', service); 207 debug('ServerApi::createService resolves', service);
209 return service; 208 return service;
210 } 209 }
211 210
@@ -231,7 +230,7 @@ export default class ServerApi {
231 data: await this._prepareServiceModel(serviceData.data), 230 data: await this._prepareServiceModel(serviceData.data),
232 }); 231 });
233 232
234 console.log('ServerApi::updateService resolves', service); 233 debug('ServerApi::updateService resolves', service);
235 return service; 234 return service;
236 } 235 }
237 236
@@ -271,7 +270,7 @@ export default class ServerApi {
271 throw new Error(request.statusText); 270 throw new Error(request.statusText);
272 } 271 }
273 const serviceData = await request.json(); 272 const serviceData = await request.json();
274 console.log('ServerApi::reorderService resolves', serviceData); 273 debug('ServerApi::reorderService resolves', serviceData);
275 return serviceData; 274 return serviceData;
276 } 275 }
277 276
@@ -286,7 +285,7 @@ export default class ServerApi {
286 285
287 removeServicePartitionDirectory(id, true); 286 removeServicePartitionDirectory(id, true);
288 287
289 console.log('ServerApi::deleteService resolves', data); 288 debug('ServerApi::deleteService resolves', data);
290 return data; 289 return data;
291 } 290 }
292 291
@@ -299,7 +298,7 @@ export default class ServerApi {
299 const data = await request.json(); 298 const data = await request.json();
300 299
301 const features = data; 300 const features = data;
302 console.log('ServerApi::getDefaultFeatures resolves', features); 301 debug('ServerApi::getDefaultFeatures resolves', features);
303 return features; 302 return features;
304 } 303 }
305 304
@@ -315,7 +314,7 @@ export default class ServerApi {
315 const data = await request.json(); 314 const data = await request.json();
316 315
317 const features = data; 316 const features = data;
318 console.log('ServerApi::getFeatures resolves', features); 317 debug('ServerApi::getFeatures resolves', features);
319 return features; 318 return features;
320 } 319 }
321 320
@@ -340,7 +339,7 @@ export default class ServerApi {
340 // eslint-disable-next-line unicorn/prefer-spread 339 // eslint-disable-next-line unicorn/prefer-spread
341 this.recipes = this.recipes.concat(this._getDevRecipes()); 340 this.recipes = this.recipes.concat(this._getDevRecipes());
342 341
343 console.log('StubServerApi::getInstalledRecipes resolves', this.recipes); 342 debug('StubServerApi::getInstalledRecipes resolves', this.recipes);
344 return this.recipes; 343 return this.recipes;
345 } 344 }
346 345
@@ -353,7 +352,7 @@ export default class ServerApi {
353 throw new Error(request.statusText); 352 throw new Error(request.statusText);
354 } 353 }
355 const recipes = await request.json(); 354 const recipes = await request.json();
356 console.log('ServerApi::getRecipeUpdates resolves', recipes); 355 debug('ServerApi::getRecipeUpdates resolves', recipes);
357 return recipes; 356 return recipes;
358 } 357 }
359 358
@@ -363,7 +362,7 @@ export default class ServerApi {
363 if (!request.ok) throw new Error(request.statusText); 362 if (!request.ok) throw new Error(request.statusText);
364 const data = await request.json(); 363 const data = await request.json();
365 const recipePreviews = this._mapRecipePreviewModel(data); 364 const recipePreviews = this._mapRecipePreviewModel(data);
366 console.log('ServerApi::getRecipes resolves', recipePreviews); 365 debug('ServerApi::getRecipes resolves', recipePreviews);
367 return recipePreviews; 366 return recipePreviews;
368 } 367 }
369 368
@@ -375,7 +374,7 @@ export default class ServerApi {
375 // data = this._addLocalRecipesToPreviews(data); 374 // data = this._addLocalRecipesToPreviews(data);
376 375
377 const recipePreviews = this._mapRecipePreviewModel(data); 376 const recipePreviews = this._mapRecipePreviewModel(data);
378 console.log('ServerApi::getFeaturedRecipes resolves', recipePreviews); 377 debug('ServerApi::getFeaturedRecipes resolves', recipePreviews);
379 return recipePreviews; 378 return recipePreviews;
380 } 379 }
381 380
@@ -386,7 +385,7 @@ export default class ServerApi {
386 385
387 const data = await request.json(); 386 const data = await request.json();
388 const recipePreviews = this._mapRecipePreviewModel(data); 387 const recipePreviews = this._mapRecipePreviewModel(data);
389 console.log('ServerApi::searchRecipePreviews resolves', recipePreviews); 388 debug('ServerApi::searchRecipePreviews resolves', recipePreviews);
390 return recipePreviews; 389 return recipePreviews;
391 } 390 }
392 391
@@ -402,21 +401,21 @@ export default class ServerApi {
402 let archivePath: PathOrFileDescriptor; 401 let archivePath: PathOrFileDescriptor;
403 402
404 if (pathExistsSync(internalRecipeFile)) { 403 if (pathExistsSync(internalRecipeFile)) {
405 console.log('[ServerApi::getRecipePackage] Using internal recipe file'); 404 debug('[ServerApi::getRecipePackage] Using internal recipe file');
406 archivePath = internalRecipeFile; 405 archivePath = internalRecipeFile;
407 } else { 406 } else {
408 console.log('[ServerApi::getRecipePackage] Downloading recipe from server'); 407 debug('[ServerApi::getRecipePackage] Downloading recipe from server');
409 archivePath = tempArchivePath; 408 archivePath = tempArchivePath;
410 409
411 const packageUrl = `${apiBase()}/recipes/download/${recipeId}`; 410 const packageUrl = `${apiBase()}/recipes/download/${recipeId}`;
412 411
413 const res = await window.fetch(packageUrl); 412 const res = await window.fetch(packageUrl);
414 console.log('Recipe downloaded', recipeId); 413 debug('Recipe downloaded', recipeId);
415 const blob = await res.blob(); 414 const blob = await res.blob();
416 const buffer = await blob.arrayBuffer(); 415 const buffer = await blob.arrayBuffer();
417 writeFileSync(tempArchivePath, Buffer.from(buffer)); 416 writeFileSync(tempArchivePath, Buffer.from(buffer));
418 } 417 }
419 console.log(archivePath); 418 debug(archivePath);
420 419
421 await sleep(10); 420 await sleep(10);
422 421
@@ -427,7 +426,7 @@ export default class ServerApi {
427 preservePaths: true, 426 preservePaths: true,
428 unlink: true, 427 unlink: true,
429 preserveOwner: false, 428 preserveOwner: false,
430 onwarn: x => console.log('warn', recipeId, x), 429 onwarn: x => debug('warn', recipeId, x),
431 }); 430 });
432 431
433 await sleep(10); 432 await sleep(10);
@@ -457,7 +456,7 @@ export default class ServerApi {
457 if (!request.ok) { 456 if (!request.ok) {
458 throw new Error(request.statusText); 457 throw new Error(request.statusText);
459 } 458 }
460 console.log('ServerApi::healthCheck resolves'); 459 debug('ServerApi::healthCheck resolves');
461 } 460 }
462 461
463 async getLegacyServices() { 462 async getLegacyServices() {
@@ -484,7 +483,7 @@ export default class ServerApi {
484 }), 483 }),
485 ); 484 );
486 485
487 console.log('ServerApi::getLegacyServices resolves', services); 486 debug('ServerApi::getLegacyServices resolves', services);
488 return services; 487 return services;
489 } 488 }
490 } catch { 489 } catch {
@@ -517,7 +516,7 @@ export default class ServerApi {
517 516
518 return new ServiceModel(service, recipe); 517 return new ServiceModel(service, recipe);
519 } catch (error) { 518 } catch (error) {
520 console.log(error); 519 debug(error);
521 return null; 520 return null;
522 } 521 }
523 } 522 }
@@ -540,7 +539,7 @@ export default class ServerApi {
540 539
541 await this.getRecipePackage(recipeId); 540 await this.getRecipePackage(recipeId);
542 541
543 console.log('Rerun ServerAPI::getInstalledRecipes'); 542 debug('Rerun ServerAPI::getInstalledRecipes');
544 await this.getInstalledRecipes(); 543 await this.getInstalledRecipes();
545 544
546 recipe = this.recipes.find(r => r.id === recipeId); 545 recipe = this.recipes.find(r => r.id === recipeId);
@@ -605,7 +604,7 @@ export default class ServerApi {
605 604
606 return recipes; 605 return recipes;
607 } catch { 606 } catch {
608 console.log('Could not load dev recipes'); 607 debug('Could not load dev recipes');
609 return false; 608 return false;
610 } 609 }
611 } 610 }
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';
7 7
8import ServiceModel from '../../../models/Service'; 8import ServiceModel from '../../../models/Service';
9 9
10// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 10const debug = require('../../../preload-safe-debug')('Ferdium:Services');
11// const debug = require('debug')('Ferdium:Services');
12 11
13class ServiceWebview extends Component { 12class ServiceWebview extends Component {
14 static propTypes = { 13 static propTypes = {
@@ -28,7 +27,7 @@ class ServiceWebview extends Component {
28 () => { 27 () => {
29 if (this.webview && this.webview.view) { 28 if (this.webview && this.webview.view) {
30 this.webview.view.addEventListener('console-message', e => { 29 this.webview.view.addEventListener('console-message', e => {
31 console.log('Service logged a message:', e.message); 30 debug('Service logged a message:', e.message);
32 }); 31 });
33 this.webview.view.addEventListener('did-navigate', () => { 32 this.webview.view.addEventListener('did-navigate', () => {
34 if (this.props.service._webview) { 33 if (this.props.service._webview) {
@@ -51,7 +50,7 @@ class ServiceWebview extends Component {
51 50
52 refocusWebview = () => { 51 refocusWebview = () => {
53 const { webview } = this; 52 const { webview } = this;
54 console.log('Refocus Webview is called', this.props.service); 53 debug('Refocus Webview is called', this.props.service);
55 if (!webview) return; 54 if (!webview) return;
56 if (this.props.service.isActive) { 55 if (this.props.service.isActive) {
57 webview.view.blur(); 56 webview.view.blur();
@@ -64,7 +63,7 @@ class ServiceWebview extends Component {
64 } ${`- ${this.props.service._webview.getTitle()}`}`; 63 } ${`- ${this.props.service._webview.getTitle()}`}`;
65 }, 100); 64 }, 100);
66 } else { 65 } else {
67 console.log('Refocus not required - Not active service'); 66 debug('Refocus not required - Not active service');
68 } 67 }
69 }; 68 };
70 69
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';
31import globalMessages from '../../../i18n/globalMessages'; 31import globalMessages from '../../../i18n/globalMessages';
32import { Icon } from '../../ui/icon'; 32import { Icon } from '../../ui/icon';
33 33
34const debug = require('debug')('Ferdium:EditSettingsForm'); 34const debug = require('../../../preload-safe-debug')('Ferdium:EditSettingsForm');
35 35
36const messages = defineMessages({ 36const messages = defineMessages({
37 headlineGeneral: { 37 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';
37import WorkspacesStore from '../../features/workspaces/store'; 37import WorkspacesStore from '../../features/workspaces/store';
38import ServicesStore from '../../stores/ServicesStore'; 38import ServicesStore from '../../stores/ServicesStore';
39 39
40const debug = require('debug')('Ferdium:EditSettingsScreen'); 40const debug = require('../../preload-safe-debug')('Ferdium:EditSettingsScreen');
41 41
42const messages = defineMessages({ 42const messages = defineMessages({
43 autoLaunchOnStart: { 43 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';
2import { pathExistsSync, outputJsonSync, readJsonSync } from 'fs-extra'; 2import { pathExistsSync, outputJsonSync, readJsonSync } from 'fs-extra';
3import { userDataPath } from '../environment-remote'; 3import { userDataPath } from '../environment-remote';
4 4
5const debug = require('debug')('Ferdium:Settings'); 5const debug = require('../preload-safe-debug')('Ferdium:Settings');
6 6
7export default class Settings { 7export default class Settings {
8 type = ''; 8 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';
2import { autoUpdater } from 'electron-updater'; 2import { autoUpdater } from 'electron-updater';
3import { isMac, isWindows } from '../../environment'; 3import { isMac, isWindows } from '../../environment';
4 4
5const debug = require('debug')('Ferdium:ipcApi:autoUpdate'); 5const debug = require('../../preload-safe-debug')('Ferdium:ipcApi:autoUpdate');
6 6
7export default (params: { mainWindow: BrowserWindow; settings: any }) => { 7export default (params: { mainWindow: BrowserWindow; settings: any }) => {
8 const enableUpdate = Boolean(params.settings.app.get('automaticUpdates')); 8 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';
2// @ts-ignore 2// @ts-ignore
3import cld from 'cld'; 3import cld from 'cld';
4 4
5const debug = require('debug')('Ferdium:ipcApi:cld'); 5const debug = require('../../preload-safe-debug')('Ferdium:ipcApi:cld');
6 6
7export default async () => { 7export default async () => {
8 ipcMain.handle('detect-language', async (_event, { sample }) => { 8 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';
3 3
4const { getDoNotDisturb } = require('macos-notification-state'); 4const { getDoNotDisturb } = require('macos-notification-state');
5 5
6const debug = require('debug')('Ferdium:ipcApi:dnd'); 6const debug = require('../../preload-safe-debug')('Ferdium:ipcApi:dnd');
7 7
8export default async () => { 8export default async () => {
9 ipcMain.handle('get-dnd', async () => { 9 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';
4import { writeFileSync } from 'fs-extra'; 4import { writeFileSync } from 'fs-extra';
5import { PathLike } from 'fs'; 5import { PathLike } from 'fs';
6 6
7// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 7const debug = require('../../preload-safe-debug')('Ferdium:ipcApi:download');
8// const debug = require('debug')('Ferdium:ipcApi:download');
9 8
10function decodeBase64Image(dataString: string) { 9function decodeBase64Image(dataString: string) {
11 const matches = dataString.match(/^data:([+/A-Za-z-]+);base64,(.+)$/); 10 const matches = dataString.match(/^data:([+/A-Za-z-]+);base64,(.+)$/);
@@ -28,7 +27,7 @@ export default (params: { mainWindow: BrowserWindow }) => {
28 const dl = await download(win!, url, { 27 const dl = await download(win!, url, {
29 saveAs: true, 28 saveAs: true,
30 }); 29 });
31 console.log('File saved to', dl.savePath); 30 debug('File saved to', dl.savePath);
32 } else { 31 } else {
33 const extension = mime.extension(fileOptions.mime); 32 const extension = mime.extension(fileOptions.mime);
34 const filename = `${fileOptions.name}.${extension}`; 33 const filename = `${fileOptions.name}.${extension}`;
@@ -47,7 +46,7 @@ export default (params: { mainWindow: BrowserWindow }) => {
47 'binary', 46 'binary',
48 ); 47 );
49 48
50 console.log('File blob saved to', saveDialog.filePath); 49 debug('File blob saved to', saveDialog.filePath);
51 } catch (error) { 50 } catch (error) {
52 console.error(error); 51 console.error(error);
53 } 52 }
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';
2 2
3import { TODOS_PARTITION_ID } from '../../config'; 3import { TODOS_PARTITION_ID } from '../../config';
4 4
5// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 5const debug = require('../../preload-safe-debug')('Ferdium:ipcApi:sessionStorage');
6// const debug = require('debug')('Ferdium:ipcApi:sessionStorage');
7 6
8function deduceSession(serviceId: string | undefined | null): Session { 7function deduceSession(serviceId: string | undefined | null): Session {
9 if (serviceId) { 8 if (serviceId) {
@@ -22,14 +21,14 @@ export default async () => {
22 const serviceSession = deduceSession(serviceId); 21 const serviceSession = deduceSession(serviceId);
23 serviceSession.flushStorageData(); 22 serviceSession.flushStorageData();
24 if (targetsToClear) { 23 if (targetsToClear) {
25 console.log('Clearing targets:', targetsToClear); 24 debug('Clearing targets:', targetsToClear);
26 serviceSession.clearStorageData(targetsToClear); 25 serviceSession.clearStorageData(targetsToClear);
27 } else { 26 } else {
28 console.log('Clearing all targets'); 27 debug('Clearing all targets');
29 serviceSession.clearStorageData(); 28 serviceSession.clearStorageData();
30 } 29 }
31 } catch (error) { 30 } catch (error) {
32 console.log(error); 31 debug(error);
33 } 32 }
34 }); 33 });
35 34
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';
6import { askForScreenCaptureAccess } from 'node-mac-permissions'; 6import { askForScreenCaptureAccess } from 'node-mac-permissions';
7import { userDataPath } from '../environment-remote'; 7import { userDataPath } from '../environment-remote';
8 8
9// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 9const debug = require('../preload-safe-debug')('Ferdium:macOSPermissions');
10// const debug = require('debug')('Ferdium:macOSPermissions');
11 10
12const isExplicitScreenCapturePermissionReqd = 11const isExplicitScreenCapturePermissionReqd =
13 macosVersion.isGreaterThanOrEqualTo('10.15'); 12 macosVersion.isGreaterThanOrEqualTo('10.15');
14console.log( 13debug(
15 `Should check explicitly for screen-capture permissions: ${isExplicitScreenCapturePermissionReqd}`, 14 `Should check explicitly for screen-capture permissions: ${isExplicitScreenCapturePermissionReqd}`,
16); 15);
17 16
@@ -22,7 +21,7 @@ function hasPromptedForScreenCapturePermission(): string | boolean {
22 return false; 21 return false;
23 } 22 }
24 23
25 console.log('Checking if status file exists'); 24 debug('Checking if status file exists');
26 return filePath && pathExistsSync(filePath); 25 return filePath && pathExistsSync(filePath);
27} 26}
28 27
@@ -32,7 +31,7 @@ function hasScreenCapturePermissionAlreadyBeenGranted(): boolean {
32 } 31 }
33 32
34 const screenCaptureStatus = systemPreferences.getMediaAccessStatus('screen'); 33 const screenCaptureStatus = systemPreferences.getMediaAccessStatus('screen');
35 console.log(`screen-capture permissions status: ${screenCaptureStatus}`); 34 debug(`screen-capture permissions status: ${screenCaptureStatus}`);
36 return screenCaptureStatus === 'granted'; 35 return screenCaptureStatus === 'granted';
37} 36}
38 37
@@ -50,18 +49,18 @@ function createStatusFile() {
50} 49}
51 50
52export const askFormacOSPermissions = async (mainWindow: BrowserWindow) => { 51export const askFormacOSPermissions = async (mainWindow: BrowserWindow) => {
53 console.log('Checking camera & microphone permissions'); 52 debug('Checking camera & microphone permissions');
54 systemPreferences.askForMediaAccess('camera'); 53 systemPreferences.askForMediaAccess('camera');
55 systemPreferences.askForMediaAccess('microphone'); 54 systemPreferences.askForMediaAccess('microphone');
56 55
57 if (hasScreenCapturePermissionAlreadyBeenGranted()) { 56 if (hasScreenCapturePermissionAlreadyBeenGranted()) {
58 console.log('Already obtained screen-capture permissions - writing status file'); 57 debug('Already obtained screen-capture permissions - writing status file');
59 createStatusFile(); 58 createStatusFile();
60 return; 59 return;
61 } 60 }
62 61
63 if (!hasPromptedForScreenCapturePermission()) { 62 if (!hasPromptedForScreenCapturePermission()) {
64 console.log('Checking screen capture permissions'); 63 debug('Checking screen capture permissions');
65 64
66 const { response } = await dialog.showMessageBox(mainWindow, { 65 const { response } = await dialog.showMessageBox(mainWindow, {
67 type: 'info', 66 type: 'info',
@@ -74,11 +73,11 @@ export const askFormacOSPermissions = async (mainWindow: BrowserWindow) => {
74 }); 73 });
75 74
76 if (response === 0) { 75 if (response === 0) {
77 console.log('Asking for access'); 76 debug('Asking for access');
78 askForScreenCaptureAccess(); 77 askForScreenCaptureAccess();
79 createStatusFile(); 78 createStatusFile();
80 } else if (response === 1) { 79 } else if (response === 1) {
81 console.log("Don't ask again"); 80 debug("Don't ask again");
82 createStatusFile(); 81 createStatusFile();
83 } 82 }
84 } 83 }
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';
2 2
3import { state as ModalState } from './store'; 3import { state as ModalState } from './store';
4 4
5const debug = require('debug')('Ferdium:feature:basicAuth'); 5const debug = require('../../preload-safe-debug')('Ferdium:feature:basicAuth');
6 6
7const state = ModalState; 7const state = ModalState;
8 8
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 @@
1import { BrowserWindow } from 'electron'; 1import { BrowserWindow } from 'electron';
2 2
3const debug = require('debug')('Ferdium:feature:basicAuth:main'); 3const debug = require('../../preload-safe-debug')('Ferdium:feature:basicAuth:main');
4 4
5export default function mainIpcHandler(mainWindow: BrowserWindow, authInfo) { 5export default function mainIpcHandler(mainWindow: BrowserWindow, authInfo) {
6 debug('Sending basic auth call', authInfo); 6 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 @@
1import { observable } from 'mobx'; 1import { observable } from 'mobx';
2import { ipcRenderer } from 'electron'; 2import { ipcRenderer } from 'electron';
3 3
4const debug = require('debug')('Ferdium:feature:basicAuth'); 4const debug = require('../../preload-safe-debug')('Ferdium:feature:basicAuth');
5 5
6const defaultState = { 6const defaultState = {
7 isModalVisible: true, 7 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 @@
1import { computed } from 'mobx'; 1import { computed } from 'mobx';
2import { FeatureStore } from '../utils/FeatureStore'; 2import { FeatureStore } from '../utils/FeatureStore';
3 3
4// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 4const debug = require('../../preload-safe-debug')('Ferdium:feature:communityRecipes:store');
5// const debug = require('debug')('Ferdium:feature:communityRecipes:store');
6 5
7export class CommunityRecipesStore extends FeatureStore { 6export class CommunityRecipesStore extends FeatureStore {
8 stores: any; 7 stores: any;
@@ -10,13 +9,13 @@ export class CommunityRecipesStore extends FeatureStore {
10 actions: any; 9 actions: any;
11 10
12 start(stores: any, actions: any) { 11 start(stores: any, actions: any) {
13 console.log('start'); 12 debug('start');
14 this.stores = stores; 13 this.stores = stores;
15 this.actions = actions; 14 this.actions = actions;
16 } 15 }
17 16
18 stop() { 17 stop() {
19 console.log('stop'); 18 debug('stop');
20 super.stop(); 19 super.stop();
21 } 20 }
22 21
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';
14import AppStore from '../../stores/AppStore'; 14import AppStore from '../../stores/AppStore';
15import ServicesStore from '../../stores/ServicesStore'; 15import ServicesStore from '../../stores/ServicesStore';
16 16
17const debug = require('debug')('Ferdium:feature:publishDebugInfo'); 17const debug = require('../../preload-safe-debug')('Ferdium:feature:publishDebugInfo');
18 18
19const messages = defineMessages({ 19const messages = defineMessages({
20 title: { 20 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';
3export { default as Component } from './Component'; 3export { default as Component } from './Component';
4 4
5const state = ModalState; 5const state = ModalState;
6const debug = require('debug')('Ferdium:feature:publishDebugInfo'); 6const debug = require('../../preload-safe-debug')('Ferdium:feature:publishDebugInfo');
7 7
8export default function initialize() { 8export default function initialize() {
9 debug('Initialize publishDebugInfo feature'); 9 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';
3export { default as Component } from './Component'; 3export { default as Component } from './Component';
4const state = ModalState; 4const state = ModalState;
5 5
6const debug = require('debug')('Ferdium:feature:quickSwitch'); 6const debug = require('../../preload-safe-debug')('Ferdium:feature:quickSwitch');
7 7
8export default function initialize() { 8export default function initialize() {
9 debug('Initialize quickSwitch feature'); 9 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 @@
1import { autorun, observable } from 'mobx'; 1import { autorun, observable } from 'mobx';
2import { session } from '@electron/remote'; 2import { session } from '@electron/remote';
3 3
4// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 4const debug = require('../../preload-safe-debug')('Ferdium:feature:serviceProxy');
5// const debug = require('debug')('Ferdium:feature:serviceProxy');
6 5
7export const config = observable({ 6export const config = observable({
8 isEnabled: true, 7 isEnabled: true,
@@ -12,7 +11,7 @@ export default function init(stores: {
12 services: { enabled: any }; 11 services: { enabled: any };
13 settings: { proxy: any }; 12 settings: { proxy: any };
14}) { 13}) {
15 console.log('Initializing `serviceProxy` feature'); 14 debug('Initializing `serviceProxy` feature');
16 15
17 autorun(() => { 16 autorun(() => {
18 config.isEnabled = true; 17 config.isEnabled = true;
@@ -20,7 +19,7 @@ export default function init(stores: {
20 const services = stores.services.enabled; 19 const services = stores.services.enabled;
21 const proxySettings = stores.settings.proxy; 20 const proxySettings = stores.settings.proxy;
22 21
23 console.log('Service Proxy autorun'); 22 debug('Service Proxy autorun');
24 23
25 for (const service of services) { 24 for (const service of services) {
26 const s = session.fromPartition(`persist:service-${service.id}`); 25 const s = session.fromPartition(`persist:service-${service.id}`);
@@ -36,14 +35,14 @@ export default function init(stores: {
36 const proxyHost = `${serviceProxyConfig.host}${ 35 const proxyHost = `${serviceProxyConfig.host}${
37 serviceProxyConfig.port ? `:${serviceProxyConfig.port}` : '' 36 serviceProxyConfig.port ? `:${serviceProxyConfig.port}` : ''
38 }`; 37 }`;
39 console.log( 38 debug(
40 `Setting proxy config from service settings for "${service.name}" (${service.id}) to`, 39 `Setting proxy config from service settings for "${service.name}" (${service.id}) to`,
41 proxyHost, 40 proxyHost,
42 ); 41 );
43 42
44 s.setProxy({ proxyRules: proxyHost }) 43 s.setProxy({ proxyRules: proxyHost })
45 .then(() => { 44 .then(() => {
46 console.log( 45 debug(
47 `Using proxy "${proxyHost}" for "${service.name}" (${service.id})`, 46 `Using proxy "${proxyHost}" for "${service.name}" (${service.id})`,
48 ); 47 );
49 }) 48 })
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 @@
1import { ipcRenderer } from 'electron'; 1import { ipcRenderer } from 'electron';
2import { IPC } from './constants'; 2import { IPC } from './constants';
3 3
4// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 4const debug = require('../../preload-safe-debug')('Ferdium:feature:todos:preload');
5// const debug = require('debug')('Ferdium:feature:todos:preload');
6 5
7console.log('Preloading Todos Webview'); 6debug('Preloading Todos Webview');
8 7
9let hostMessageListener = ({ action }) => { 8let hostMessageListener = ({ action }) => {
10 switch (action) { 9 switch (action) {
@@ -28,7 +27,7 @@ window['ferdium'] = {
28}; 27};
29 28
30ipcRenderer.on(IPC.TODOS_HOST_CHANNEL, (event, message) => { 29ipcRenderer.on(IPC.TODOS_HOST_CHANNEL, (event, message) => {
31 console.log('Received host message', event, message); 30 debug('Received host message', event, message);
32 hostMessageListener(message); 31 hostMessageListener(message);
33}); 32});
34 33
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';
18import { IPC, TODOS_ROUTES } from './constants'; 18import { IPC, TODOS_ROUTES } from './constants';
19import UserAgent from '../../models/UserAgent'; 19import UserAgent from '../../models/UserAgent';
20 20
21// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 21const debug = require('../../preload-safe-debug')('Ferdium:feature:todos:store');
22// const debug = require('debug')('Ferdium:feature:todos:store');
23 22
24export default class TodoStore extends FeatureStore { 23export default class TodoStore extends FeatureStore {
25 @observable stores = null; 24 @observable stores = null;
@@ -97,7 +96,7 @@ export default class TodoStore extends FeatureStore {
97 // ========== PUBLIC API ========= // 96 // ========== PUBLIC API ========= //
98 97
99 @action start(stores, actions) { 98 @action start(stores, actions) {
100 console.log('TodoStore::start'); 99 debug('TodoStore::start');
101 this.stores = stores; 100 this.stores = stores;
102 this.actions = actions; 101 this.actions = actions;
103 102
@@ -134,7 +133,7 @@ export default class TodoStore extends FeatureStore {
134 133
135 @action stop() { 134 @action stop() {
136 super.stop(); 135 super.stop();
137 console.log('TodoStore::stop'); 136 debug('TodoStore::stop');
138 this.reset(); 137 this.reset();
139 this.isFeatureActive = false; 138 this.isFeatureActive = false;
140 } 139 }
@@ -163,7 +162,7 @@ export default class TodoStore extends FeatureStore {
163 }; 162 };
164 163
165 @action _setTodosWebview = ({ webview }) => { 164 @action _setTodosWebview = ({ webview }) => {
166 console.log('_setTodosWebview', webview); 165 debug('_setTodosWebview', webview);
167 if (this.webview !== webview) { 166 if (this.webview !== webview) {
168 this.webview = webview; 167 this.webview = webview;
169 this.userAgentModel.setWebviewReference(webview); 168 this.userAgentModel.setWebviewReference(webview);
@@ -171,14 +170,14 @@ export default class TodoStore extends FeatureStore {
171 }; 170 };
172 171
173 @action _handleHostMessage = message => { 172 @action _handleHostMessage = message => {
174 console.log('_handleHostMessage', message); 173 debug('_handleHostMessage', message);
175 if (message.action === 'todos:create') { 174 if (message.action === 'todos:create') {
176 this.webview.send(IPC.TODOS_HOST_CHANNEL, message); 175 this.webview.send(IPC.TODOS_HOST_CHANNEL, message);
177 } 176 }
178 }; 177 };
179 178
180 @action _handleClientMessage = ({ channel, message = {} }) => { 179 @action _handleClientMessage = ({ channel, message = {} }) => {
181 console.log('_handleClientMessage', channel, message); 180 debug('_handleClientMessage', channel, message);
182 switch (message.action) { 181 switch (message.action) {
183 case 'todos:initialized': 182 case 'todos:initialized':
184 this._onTodosClientInitialized(); 183 this._onTodosClientInitialized();
@@ -187,7 +186,7 @@ export default class TodoStore extends FeatureStore {
187 this._goToService(message.data); 186 this._goToService(message.data);
188 break; 187 break;
189 default: 188 default:
190 console.log('Other message received', channel, message); 189 debug('Other message received', channel, message);
191 if (this.stores.services.isTodosServiceAdded) { 190 if (this.stores.services.isTodosServiceAdded) {
192 this.actions.service.handleIPCMessage({ 191 this.actions.service.handleIPCMessage({
193 serviceId: this.stores.services.isTodosServiceAdded.id, 192 serviceId: this.stores.services.isTodosServiceAdded.id,
@@ -203,7 +202,7 @@ export default class TodoStore extends FeatureStore {
203 }; 202 };
204 203
205 @action _toggleTodosFeatureVisibility = () => { 204 @action _toggleTodosFeatureVisibility = () => {
206 console.log('_toggleTodosFeatureVisibility'); 205 debug('_toggleTodosFeatureVisibility');
207 206
208 this._updateSettings({ 207 this._updateSettings({
209 isFeatureEnabledByUser: !this.settings.isFeatureEnabledByUser, 208 isFeatureEnabledByUser: !this.settings.isFeatureEnabledByUser,
@@ -211,14 +210,14 @@ export default class TodoStore extends FeatureStore {
211 }; 210 };
212 211
213 _openDevTools = () => { 212 _openDevTools = () => {
214 console.log('_openDevTools'); 213 debug('_openDevTools');
215 214
216 const webview = document.querySelector('#todos-panel webview'); 215 const webview = document.querySelector('#todos-panel webview');
217 if (webview) webview.openDevTools(); 216 if (webview) webview.openDevTools();
218 }; 217 };
219 218
220 _reload = () => { 219 _reload = () => {
221 console.log('_reload'); 220 debug('_reload');
222 221
223 const webview = document.querySelector('#todos-panel webview'); 222 const webview = document.querySelector('#todos-panel webview');
224 if (webview) webview.reload(); 223 if (webview) webview.reload();
@@ -286,7 +285,7 @@ export default class TodoStore extends FeatureStore {
286 const { pathname } = this.stores.router.location; 285 const { pathname } = this.stores.router.location;
287 286
288 if (pathname === TODOS_ROUTES.TARGET) { 287 if (pathname === TODOS_ROUTES.TARGET) {
289 console.log('Router is on todos route, show todos panel'); 288 debug('Router is on todos route, show todos panel');
290 // todosStore.start(stores, actions); 289 // todosStore.start(stores, actions);
291 this.stores.router.push('/'); 290 this.stores.router.push('/');
292 291
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';
4import Workspace from './models/Workspace'; 4import Workspace from './models/Workspace';
5import apiBase from '../../api/apiBase'; 5import apiBase from '../../api/apiBase';
6 6
7// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 7const debug = require('../../preload-safe-debug')('Ferdium:feature:workspaces:api');
8// const debug = require('debug')('Ferdium:feature:workspaces:api');
9 8
10export const workspaceApi = { 9export const workspaceApi = {
11 getUserWorkspaces: async () => { 10 getUserWorkspaces: async () => {
12 const url = `${apiBase()}/workspace`; 11 const url = `${apiBase()}/workspace`;
13 console.log('getUserWorkspaces GET', url); 12 debug('getUserWorkspaces GET', url);
14 const result = await sendAuthRequest(url, { method: 'GET' }); 13 const result = await sendAuthRequest(url, { method: 'GET' });
15 console.log('getUserWorkspaces RESULT', result); 14 debug('getUserWorkspaces RESULT', result);
16 if (!result.ok) { 15 if (!result.ok) {
17 throw new Error("Couldn't getUserWorkspaces"); 16 throw new Error("Couldn't getUserWorkspaces");
18 } 17 }
@@ -26,9 +25,9 @@ export const workspaceApi = {
26 method: 'POST', 25 method: 'POST',
27 body: JSON.stringify({ name }), 26 body: JSON.stringify({ name }),
28 }; 27 };
29 console.log('createWorkspace POST', url, options); 28 debug('createWorkspace POST', url, options);
30 const result = await sendAuthRequest(url, options); 29 const result = await sendAuthRequest(url, options);
31 console.log('createWorkspace RESULT', result); 30 debug('createWorkspace RESULT', result);
32 if (!result.ok) { 31 if (!result.ok) {
33 throw new Error("Couldn't createWorkspace"); 32 throw new Error("Couldn't createWorkspace");
34 } 33 }
@@ -37,9 +36,9 @@ export const workspaceApi = {
37 36
38 deleteWorkspace: async workspace => { 37 deleteWorkspace: async workspace => {
39 const url = `${apiBase()}/workspace/${workspace.id}`; 38 const url = `${apiBase()}/workspace/${workspace.id}`;
40 console.log('deleteWorkspace DELETE', url); 39 debug('deleteWorkspace DELETE', url);
41 const result = await sendAuthRequest(url, { method: 'DELETE' }); 40 const result = await sendAuthRequest(url, { method: 'DELETE' });
42 console.log('deleteWorkspace RESULT', result); 41 debug('deleteWorkspace RESULT', result);
43 if (!result.ok) { 42 if (!result.ok) {
44 throw new Error("Couldn't deleteWorkspace"); 43 throw new Error("Couldn't deleteWorkspace");
45 } 44 }
@@ -52,9 +51,9 @@ export const workspaceApi = {
52 method: 'PUT', 51 method: 'PUT',
53 body: JSON.stringify(pick(workspace, ['name', 'services'])), 52 body: JSON.stringify(pick(workspace, ['name', 'services'])),
54 }; 53 };
55 console.log('updateWorkspace UPDATE', url, options); 54 debug('updateWorkspace UPDATE', url, options);
56 const result = await sendAuthRequest(url, options); 55 const result = await sendAuthRequest(url, options);
57 console.log('updateWorkspace RESULT', result); 56 debug('updateWorkspace RESULT', result);
58 if (!result.ok) { 57 if (!result.ok) {
59 throw new Error("Couldn't updateWorkspace"); 58 throw new Error("Couldn't updateWorkspace");
60 } 59 }
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';
15 15
16import { KEEP_WS_LOADED_USID } from '../../config'; 16import { KEEP_WS_LOADED_USID } from '../../config';
17 17
18// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 18const debug = require('../../preload-safe-debug')('Ferdium:feature:workspaces:store');
19// const debug = require('debug')('Ferdium:feature:workspaces:store');
20 19
21export default class WorkspacesStore extends FeatureStore { 20export default class WorkspacesStore extends FeatureStore {
22 @observable isFeatureActive = false; 21 @observable isFeatureActive = false;
@@ -70,7 +69,7 @@ export default class WorkspacesStore extends FeatureStore {
70 // ========== PUBLIC API ========= // 69 // ========== PUBLIC API ========= //
71 70
72 @action start(stores, actions) { 71 @action start(stores, actions) {
73 console.log('WorkspacesStore::start'); 72 debug('WorkspacesStore::start');
74 this.stores = stores; 73 this.stores = stores;
75 this.actions = actions; 74 this.actions = actions;
76 75
@@ -116,7 +115,7 @@ export default class WorkspacesStore extends FeatureStore {
116 115
117 @action stop() { 116 @action stop() {
118 super.stop(); 117 super.stop();
119 console.log('WorkspacesStore::stop'); 118 debug('WorkspacesStore::stop');
120 this.reset(); 119 this.reset();
121 this.isFeatureActive = false; 120 this.isFeatureActive = false;
122 } 121 }
@@ -274,7 +273,7 @@ export default class WorkspacesStore extends FeatureStore {
274 }; 273 };
275 274
276 _activateLastUsedWorkspaceReaction = () => { 275 _activateLastUsedWorkspaceReaction = () => {
277 console.log('_activateLastUsedWorkspaceReaction'); 276 debug('_activateLastUsedWorkspaceReaction');
278 if (!this.activeWorkspace && this.userHasWorkspaces) { 277 if (!this.activeWorkspace && this.userHasWorkspaces) {
279 const { lastActiveWorkspace } = this.settings; 278 const { lastActiveWorkspace } = this.settings;
280 if (lastActiveWorkspace) { 279 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';
6 6
7import { ALLOWED_PROTOCOLS } from '../config'; 7import { ALLOWED_PROTOCOLS } from '../config';
8 8
9// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 9const debug = require('../preload-safe-debug')('Ferdium:Helpers:url');
10// const debug = require('debug')('Ferdium:Helpers:url');
11 10
12export function isValidExternalURL(url: string | URL) { 11export function isValidExternalURL(url: string | URL) {
13 let parsedUrl: URL; 12 let parsedUrl: URL;
@@ -19,7 +18,7 @@ export function isValidExternalURL(url: string | URL) {
19 18
20 const isAllowed = ALLOWED_PROTOCOLS.includes(parsedUrl.protocol); 19 const isAllowed = ALLOWED_PROTOCOLS.includes(parsedUrl.protocol);
21 20
22 console.log('protocol check is', isAllowed, 'for:', url); 21 debug('protocol check is', isAllowed, 'for:', url);
23 22
24 return isAllowed; 23 return isAllowed;
25} 24}
@@ -38,7 +37,7 @@ export function openExternalUrl(
38 url: string | URL, 37 url: string | URL,
39 skipValidityCheck: boolean = false, 38 skipValidityCheck: boolean = false,
40) { 39) {
41 console.log('Open url:', url, 'with skipValidityCheck:', skipValidityCheck); 40 debug('Open url:', url, 'with skipValidityCheck:', skipValidityCheck);
42 if (skipValidityCheck || isValidExternalURL(url)) { 41 if (skipValidityCheck || isValidExternalURL(url)) {
43 shell.openExternal(url.toString()); 42 shell.openExternal(url.toString());
44 } 43 }
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 @@
28 require('./sentry'); 28 require('./sentry');
29 const { isDevMode } = require('./environment-remote'); 29 const { isDevMode } = require('./environment-remote');
30 if (isDevMode) { 30 if (isDevMode) {
31 // Here we must access `debug` directly (instead of through `preload-safe-debug`),
32 // because we need to set the log level.
33 // However, this is safe, because we aren't in a preload script.
31 const debugging = require('debug'); 34 const debugging = require('debug');
32 debugging.enable(process.env.DEBUG); 35 debugging.enable(process.env.DEBUG);
33 36
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 {
12import { emptyDirSync, ensureFileSync } from 'fs-extra'; 12import { emptyDirSync, ensureFileSync } from 'fs-extra';
13import { join } from 'path'; 13import { join } from 'path';
14import windowStateKeeper from 'electron-window-state'; 14import windowStateKeeper from 'electron-window-state';
15import minimist from 'minimist';
15import ms from 'ms'; 16import ms from 'ms';
16import { enableWebContents, initializeRemote } from './electron-util'; 17import { enableWebContents, initializeRemote } from './electron-util';
17import { enforceMacOSAppLocation } from './enforce-macos-app-location'; 18import { enforceMacOSAppLocation } from './enforce-macos-app-location';
@@ -44,11 +45,10 @@ import { asarPath } from './helpers/asar-helpers';
44import { openExternalUrl } from './helpers/url-helpers'; 45import { openExternalUrl } from './helpers/url-helpers';
45import userAgent from './helpers/userAgent-helpers'; 46import userAgent from './helpers/userAgent-helpers';
46 47
47// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 48const debug = require('./preload-safe-debug')('Ferdium:App');
48// const debug = require('debug')('Ferdium:App');
49 49
50// Globally set useragent to fix user agent override in service workers 50// Globally set useragent to fix user agent override in service workers
51console.log('Set userAgent to', userAgent()); 51debug('Set userAgent to ', userAgent());
52app.userAgentFallback = userAgent(); 52app.userAgentFallback = userAgent();
53 53
54// Keep a global reference of the window object, if you don't, the window will 54// Keep a global reference of the window object, if you don't, the window will
@@ -127,7 +127,7 @@ if (!gotTheLock) {
127 if (argv.includes('--reset-window')) { 127 if (argv.includes('--reset-window')) {
128 // Needs to be delayed to not interfere with mainWindow.restore(); 128 // Needs to be delayed to not interfere with mainWindow.restore();
129 setTimeout(() => { 129 setTimeout(() => {
130 console.log('Resetting windows via Task'); 130 debug('Resetting windows via Task');
131 window.setPosition( 131 window.setPosition(
132 DEFAULT_WINDOW_OPTIONS.x + 100, 132 DEFAULT_WINDOW_OPTIONS.x + 100,
133 DEFAULT_WINDOW_OPTIONS.y + 100, 133 DEFAULT_WINDOW_OPTIONS.y + 100,
@@ -140,7 +140,7 @@ if (!gotTheLock) {
140 } else if (argv.includes('--quit')) { 140 } else if (argv.includes('--quit')) {
141 // Needs to be delayed to not interfere with mainWindow.restore(); 141 // Needs to be delayed to not interfere with mainWindow.restore();
142 setTimeout(() => { 142 setTimeout(() => {
143 console.log('Quitting Ferdium via Task'); 143 debug('Quitting Ferdium via Task');
144 app.quit(); 144 app.quit();
145 }, 1); 145 }, 1);
146 } 146 }
@@ -162,7 +162,7 @@ if (
162 162
163// Disable GPU acceleration 163// Disable GPU acceleration
164if (!retrieveSettingValue('enableGPUAcceleration', false)) { 164if (!retrieveSettingValue('enableGPUAcceleration', false)) {
165 console.log('Disable GPU Acceleration'); 165 debug('Disable GPU Acceleration');
166 app.disableHardwareAcceleration(); 166 app.disableHardwareAcceleration();
167} 167}
168 168
@@ -184,7 +184,7 @@ const createWindow = () => {
184 let posY = mainWindowState.y || DEFAULT_WINDOW_OPTIONS.y; 184 let posY = mainWindowState.y || DEFAULT_WINDOW_OPTIONS.y;
185 185
186 if (!isPositionValid({ x: posX, y: posY })) { 186 if (!isPositionValid({ x: posX, y: posY })) {
187 console.log('Window is out of screen bounds, resetting window'); 187 debug('Window is out of screen bounds, resetting window');
188 posX = DEFAULT_WINDOW_OPTIONS.x; 188 posX = DEFAULT_WINDOW_OPTIONS.x;
189 posY = DEFAULT_WINDOW_OPTIONS.y; 189 posY = DEFAULT_WINDOW_OPTIONS.y;
190 } 190 }
@@ -285,7 +285,7 @@ const createWindow = () => {
285 285
286 // Emitted when the window is closed. 286 // Emitted when the window is closed.
287 mainWindow.on('close', e => { 287 mainWindow.on('close', e => {
288 console.log('Window: close window'); 288 debug('Window: close window');
289 // Dereference the window object, usually you would store windows 289 // Dereference the window object, usually you would store windows
290 // in an array if your app supports multi windows, this is the time 290 // in an array if your app supports multi windows, this is the time
291 // when you should delete the corresponding element. 291 // when you should delete the corresponding element.
@@ -298,7 +298,7 @@ const createWindow = () => {
298 ) { 298 ) {
299 e.preventDefault(); 299 e.preventDefault();
300 if (isWindows) { 300 if (isWindows) {
301 console.log('Window: minimize'); 301 debug('Window: minimize');
302 mainWindow?.minimize(); 302 mainWindow?.minimize();
303 303
304 if ( 304 if (
@@ -307,16 +307,16 @@ const createWindow = () => {
307 DEFAULT_APP_SETTINGS.closeToSystemTray, 307 DEFAULT_APP_SETTINGS.closeToSystemTray,
308 ) 308 )
309 ) { 309 ) {
310 console.log('Skip taskbar: true'); 310 debug('Skip taskbar: true');
311 mainWindow?.setSkipTaskbar(true); 311 mainWindow?.setSkipTaskbar(true);
312 } 312 }
313 } else if (isMac && mainWindow?.isFullScreen()) { 313 } else if (isMac && mainWindow?.isFullScreen()) {
314 console.log('Window: leaveFullScreen and hide'); 314 debug('Window: leaveFullScreen and hide');
315 mainWindow.once('show', () => mainWindow?.setFullScreen(true)); 315 mainWindow.once('show', () => mainWindow?.setFullScreen(true));
316 mainWindow.once('leave-full-screen', () => mainWindow?.hide()); 316 mainWindow.once('leave-full-screen', () => mainWindow?.hide());
317 mainWindow.setFullScreen(false); 317 mainWindow.setFullScreen(false);
318 } else { 318 } else {
319 console.log('Window: hide'); 319 debug('Window: hide');
320 mainWindow?.hide(); 320 mainWindow?.hide();
321 } 321 }
322 } else { 322 } else {
@@ -337,31 +337,31 @@ const createWindow = () => {
337 DEFAULT_APP_SETTINGS.minimizeToSystemTray, 337 DEFAULT_APP_SETTINGS.minimizeToSystemTray,
338 ) 338 )
339 ) { 339 ) {
340 console.log('Skip taskbar: true'); 340 debug('Skip taskbar: true');
341 mainWindow?.setSkipTaskbar(true); 341 mainWindow?.setSkipTaskbar(true);
342 trayIcon.show(); 342 trayIcon.show();
343 } 343 }
344 }); 344 });
345 345
346 mainWindow.on('maximize', () => { 346 mainWindow.on('maximize', () => {
347 console.log('Window: maximize'); 347 debug('Window: maximize');
348 // @ts-expect-error Property 'isMaximized' does not exist on type 'App'. 348 // @ts-expect-error Property 'isMaximized' does not exist on type 'App'.
349 app.isMaximized = true; 349 app.isMaximized = true;
350 }); 350 });
351 351
352 mainWindow.on('unmaximize', () => { 352 mainWindow.on('unmaximize', () => {
353 console.log('Window: unmaximize'); 353 debug('Window: unmaximize');
354 // @ts-expect-error Property 'isMaximized' does not exist on type 'App'. 354 // @ts-expect-error Property 'isMaximized' does not exist on type 'App'.
355 app.isMaximized = false; 355 app.isMaximized = false;
356 }); 356 });
357 357
358 mainWindow.on('restore', () => { 358 mainWindow.on('restore', () => {
359 console.log('Window: restore'); 359 debug('Window: restore');
360 mainWindow?.setSkipTaskbar(false); 360 mainWindow?.setSkipTaskbar(false);
361 361
362 // @ts-expect-error Property 'wasMaximized' does not exist on type 'App'. 362 // @ts-expect-error Property 'wasMaximized' does not exist on type 'App'.
363 if (app.wasMaximized) { 363 if (app.wasMaximized) {
364 console.log('Window: was maximized before, maximize window'); 364 debug('Window: was maximized before, maximize window');
365 mainWindow?.maximize(); 365 mainWindow?.maximize();
366 } 366 }
367 367
@@ -371,7 +371,7 @@ const createWindow = () => {
371 DEFAULT_APP_SETTINGS.enableSystemTray, 371 DEFAULT_APP_SETTINGS.enableSystemTray,
372 ) 372 )
373 ) { 373 ) {
374 console.log('Tray: hiding tray icon'); 374 debug('Tray: hiding tray icon');
375 trayIcon.hide(); 375 trayIcon.hide();
376 } 376 }
377 }); 377 });
@@ -383,7 +383,7 @@ const createWindow = () => {
383 } 383 }
384 384
385 mainWindow.on('show', () => { 385 mainWindow.on('show', () => {
386 console.log('Skip taskbar: true'); 386 debug('Skip taskbar: true');
387 mainWindow?.setSkipTaskbar(false); 387 mainWindow?.setSkipTaskbar(false);
388 }); 388 });
389 389
@@ -423,7 +423,7 @@ const createWindow = () => {
423// used for Kerberos support 423// used for Kerberos support
424// Usage e.g. MACOS 424// Usage e.g. MACOS
425// $ Ferdium.app/Contents/MacOS/Ferdium --auth-server-whitelist *.mydomain.com --auth-negotiate-delegate-whitelist *.mydomain.com 425// $ Ferdium.app/Contents/MacOS/Ferdium --auth-server-whitelist *.mydomain.com --auth-negotiate-delegate-whitelist *.mydomain.com
426const argv = require('minimist')(process.argv.slice(1)); 426const argv = minimist(process.argv.slice(1));
427 427
428if (argv['auth-server-whitelist']) { 428if (argv['auth-server-whitelist']) {
429 app.commandLine.appendSwitch( 429 app.commandLine.appendSwitch(
@@ -500,18 +500,18 @@ let authCallback = noop;
500app.on('login', (event, _webContents, _request, authInfo, callback) => { 500app.on('login', (event, _webContents, _request, authInfo, callback) => {
501 // @ts-expect-error Type '(username?: string | undefined, password?: string | undefined) => void' is not assignable to type '() => null'. 501 // @ts-expect-error Type '(username?: string | undefined, password?: string | undefined) => void' is not assignable to type '() => null'.
502 authCallback = callback; 502 authCallback = callback;
503 console.log('browser login event', authInfo); 503 debug('browser login event', authInfo);
504 event.preventDefault(); 504 event.preventDefault();
505 505
506 if (!authInfo.isProxy && authInfo.scheme === 'basic') { 506 if (!authInfo.isProxy && authInfo.scheme === 'basic') {
507 console.log('basic auth handler', authInfo); 507 debug('basic auth handler', authInfo);
508 basicAuthHandler(mainWindow!, authInfo); 508 basicAuthHandler(mainWindow!, authInfo);
509 } 509 }
510}); 510});
511 511
512// TODO: evaluate if we need to store the authCallback for every service 512// TODO: evaluate if we need to store the authCallback for every service
513ipcMain.on('feature-basic-auth-credentials', (_e, { user, password }) => { 513ipcMain.on('feature-basic-auth-credentials', (_e, { user, password }) => {
514 console.log('Received basic auth credentials', user, '********'); 514 debug('Received basic auth credentials', user, '********');
515 515
516 // @ts-expect-error Expected 0 arguments, but got 2. 516 // @ts-expect-error Expected 0 arguments, but got 2.
517 authCallback(user, password); 517 authCallback(user, password);
@@ -530,13 +530,13 @@ ipcMain.on('open-browser-window', (_e, { url, serviceId }) => {
530 enableWebContents(child.webContents); 530 enableWebContents(child.webContents);
531 child.show(); 531 child.show();
532 child.loadURL(url); 532 child.loadURL(url);
533 console.log('Received open-browser-window', url); 533 debug('Received open-browser-window', url);
534}); 534});
535 535
536ipcMain.on( 536ipcMain.on(
537 'modifyRequestHeaders', 537 'modifyRequestHeaders',
538 (_e, { modifiedRequestHeaders, serviceId }) => { 538 (_e, { modifiedRequestHeaders, serviceId }) => {
539 console.log( 539 debug(
540 `Received modifyRequestHeaders ${modifiedRequestHeaders} for serviceId ${serviceId}`, 540 `Received modifyRequestHeaders ${modifiedRequestHeaders} for serviceId ${serviceId}`,
541 ); 541 );
542 for (const headerFilterSet of modifiedRequestHeaders) { 542 for (const headerFilterSet of modifiedRequestHeaders) {
@@ -557,7 +557,7 @@ ipcMain.on(
557); 557);
558 558
559ipcMain.on('knownCertificateHosts', (_e, { knownHosts, serviceId }) => { 559ipcMain.on('knownCertificateHosts', (_e, { knownHosts, serviceId }) => {
560 console.log( 560 debug(
561 `Received knownCertificateHosts ${knownHosts} for serviceId ${serviceId}`, 561 `Received knownCertificateHosts ${knownHosts} for serviceId ${serviceId}`,
562 ); 562 );
563 session 563 session
@@ -577,7 +577,7 @@ ipcMain.on('knownCertificateHosts', (_e, { knownHosts, serviceId }) => {
577}); 577});
578 578
579ipcMain.on('feature-basic-auth-cancel', () => { 579ipcMain.on('feature-basic-auth-cancel', () => {
580 console.log('Cancel basic auth'); 580 debug('Cancel basic auth');
581 581
582 // @ts-expect-error Expected 0 arguments, but got 2. 582 // @ts-expect-error Expected 0 arguments, but got 2.
583 authCallback(null); 583 authCallback(null);
@@ -596,7 +596,7 @@ ipcMain.on('find-in-page', (e, text, options) => {
596 } 596 }
597 } 597 }
598 const requestId = webContents.findInPage(text, sanitizedOptions); 598 const requestId = webContents.findInPage(text, sanitizedOptions);
599 console.log('Find in page', text, options, requestId); 599 debug('Find in page', text, options, requestId);
600 e.returnValue = requestId; 600 e.returnValue = requestId;
601 } else { 601 } else {
602 e.returnValue = null; 602 e.returnValue = null;
@@ -625,10 +625,10 @@ ipcMain.on('set-spellchecker-locales', (_e, { locale, serviceId }) => {
625 625
626 const serviceSession = session.fromPartition(`persist:service-${serviceId}`); 626 const serviceSession = session.fromPartition(`persist:service-${serviceId}`);
627 const [defaultLocale] = serviceSession.getSpellCheckerLanguages(); 627 const [defaultLocale] = serviceSession.getSpellCheckerLanguages();
628 console.log(`Spellchecker default locale is: ${defaultLocale}`); 628 debug(`Spellchecker default locale is: ${defaultLocale}`);
629 629
630 const locales = [locale, defaultLocale, DEFAULT_APP_SETTINGS.fallbackLocale]; 630 const locales = [locale, defaultLocale, DEFAULT_APP_SETTINGS.fallbackLocale];
631 console.log(`Setting spellchecker locales to: ${locales}`); 631 debug(`Setting spellchecker locales to: ${locales}`);
632 serviceSession.setSpellCheckerLanguages(locales); 632 serviceSession.setSpellCheckerLanguages(locales);
633}); 633});
634 634
@@ -646,10 +646,10 @@ app.on('window-all-closed', () => {
646 DEFAULT_APP_SETTINGS.runInBackground, 646 DEFAULT_APP_SETTINGS.runInBackground,
647 ) 647 )
648 ) { 648 ) {
649 console.log('Window: all windows closed, quit app'); 649 debug('Window: all windows closed, quit app');
650 app.quit(); 650 app.quit();
651 } else { 651 } else {
652 console.log("Window: don't quit app"); 652 debug("Window: don't quit app");
653 } 653 }
654}); 654});
655 655
@@ -695,7 +695,7 @@ app.on('will-finish-launching', () => {
695 event.preventDefault(); 695 event.preventDefault();
696 696
697 onDidLoad((window: BrowserWindow) => { 697 onDidLoad((window: BrowserWindow) => {
698 console.log('open-url event', url); 698 debug('open-url event', url);
699 handleDeepLink(window, url); 699 handleDeepLink(window, url);
700 }); 700 });
701 }); 701 });
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');
4const Env = use('Env'); 4const Env = use('Env');
5 5
6const fetch = require('node-fetch'); 6const fetch = require('node-fetch');
7const debug = require('debug')('Ferdium:internalServer:RecipeController'); 7const debug = require('../../../../preload-safe-debug')('Ferdium:internalServer:RecipeController');
8const { LIVE_FERDIUM_API } = require('../../../../config'); 8const { LIVE_FERDIUM_API } = require('../../../../config');
9const { API_VERSION } = require('../../../../environment-remote'); 9const { API_VERSION } = require('../../../../environment-remote');
10 10
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 {
14 ifUndefinedNumber, 14 ifUndefinedNumber,
15} from '../jsUtils'; 15} from '../jsUtils';
16 16
17// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 17const debug = require('../preload-safe-debug')('Ferdium:Service');
18// const debug = require('debug')('Ferdium:Service');
19 18
20export default class Service { 19export default class Service {
21 id = ''; 20 id = '';
@@ -306,25 +305,25 @@ export default class Service {
306 // Send those headers to ipcMain so that it can be set in session 305 // Send those headers to ipcMain so that it can be set in session
307 if (typeof this.recipe.modifyRequestHeaders === 'function') { 306 if (typeof this.recipe.modifyRequestHeaders === 'function') {
308 const modifiedRequestHeaders = this.recipe.modifyRequestHeaders(); 307 const modifiedRequestHeaders = this.recipe.modifyRequestHeaders();
309 console.log(this.name, 'modifiedRequestHeaders', modifiedRequestHeaders); 308 debug(this.name, 'modifiedRequestHeaders', modifiedRequestHeaders);
310 ipcRenderer.send('modifyRequestHeaders', { 309 ipcRenderer.send('modifyRequestHeaders', {
311 modifiedRequestHeaders, 310 modifiedRequestHeaders,
312 serviceId: this.id, 311 serviceId: this.id,
313 }); 312 });
314 } else { 313 } else {
315 console.log(this.name, 'modifyRequestHeaders is not defined in the recipe'); 314 debug(this.name, 'modifyRequestHeaders is not defined in the recipe');
316 } 315 }
317 316
318 // if the recipe has implemented 'knownCertificateHosts' 317 // if the recipe has implemented 'knownCertificateHosts'
319 if (typeof this.recipe.knownCertificateHosts === 'function') { 318 if (typeof this.recipe.knownCertificateHosts === 'function') {
320 const knownHosts = this.recipe.knownCertificateHosts(); 319 const knownHosts = this.recipe.knownCertificateHosts();
321 console.log(this.name, 'knownCertificateHosts', knownHosts); 320 debug(this.name, 'knownCertificateHosts', knownHosts);
322 ipcRenderer.send('knownCertificateHosts', { 321 ipcRenderer.send('knownCertificateHosts', {
323 knownHosts, 322 knownHosts,
324 serviceId: this.id, 323 serviceId: this.id,
325 }); 324 });
326 } else { 325 } else {
327 console.log(this.name, 'knownCertificateHosts is not defined in the recipe'); 326 debug(this.name, 'knownCertificateHosts is not defined in the recipe');
328 } 327 }
329 328
330 this.webview.addEventListener('ipc-message', async e => { 329 this.webview.addEventListener('ipc-message', async e => {
@@ -348,7 +347,7 @@ export default class Service {
348 this.webview.addEventListener( 347 this.webview.addEventListener(
349 'new-window', 348 'new-window',
350 (event, url, frameName, options) => { 349 (event, url, frameName, options) => {
351 console.log('new-window', event, url, frameName, options); 350 debug('new-window', event, url, frameName, options);
352 if (!isValidExternalURL(event.url)) { 351 if (!isValidExternalURL(event.url)) {
353 return; 352 return;
354 } 353 }
@@ -372,7 +371,7 @@ export default class Service {
372 ); 371 );
373 372
374 this.webview.addEventListener('did-start-loading', event => { 373 this.webview.addEventListener('did-start-loading', event => {
375 console.log('Did start load', this.name, event); 374 debug('Did start load', this.name, event);
376 375
377 this.hasCrashed = false; 376 this.hasCrashed = false;
378 this.isLoading = true; 377 this.isLoading = true;
@@ -391,7 +390,7 @@ export default class Service {
391 this.webview.addEventListener('did-navigate', didLoad.bind(this)); 390 this.webview.addEventListener('did-navigate', didLoad.bind(this));
392 391
393 this.webview.addEventListener('did-fail-load', event => { 392 this.webview.addEventListener('did-fail-load', event => {
394 console.log('Service failed to load', this.name, event); 393 debug('Service failed to load', this.name, event);
395 if ( 394 if (
396 event.isMainFrame && 395 event.isMainFrame &&
397 event.errorCode !== -21 && 396 event.errorCode !== -21 &&
@@ -404,33 +403,33 @@ export default class Service {
404 }); 403 });
405 404
406 this.webview.addEventListener('crashed', () => { 405 this.webview.addEventListener('crashed', () => {
407 console.log('Service crashed', this.name); 406 debug('Service crashed', this.name);
408 this.hasCrashed = true; 407 this.hasCrashed = true;
409 }); 408 });
410 409
411 this.webview.addEventListener('found-in-page', ({ result }) => { 410 this.webview.addEventListener('found-in-page', ({ result }) => {
412 console.log('Found in page', result); 411 debug('Found in page', result);
413 this.webview.send('found-in-page', result); 412 this.webview.send('found-in-page', result);
414 }); 413 });
415 414
416 webviewWebContents.on('login', (event, request, authInfo, callback) => { 415 webviewWebContents.on('login', (event, request, authInfo, callback) => {
417 // const authCallback = callback; 416 // const authCallback = callback;
418 console.log('browser login event', authInfo); 417 debug('browser login event', authInfo);
419 event.preventDefault(); 418 event.preventDefault();
420 419
421 if (authInfo.isProxy && authInfo.scheme === 'basic') { 420 if (authInfo.isProxy && authInfo.scheme === 'basic') {
422 console.log('Sending service echo ping'); 421 debug('Sending service echo ping');
423 webviewWebContents.send('get-service-id'); 422 webviewWebContents.send('get-service-id');
424 423
425 console.log('Received service id', this.id); 424 debug('Received service id', this.id);
426 425
427 const ps = stores.settings.proxy[this.id]; 426 const ps = stores.settings.proxy[this.id];
428 427
429 if (ps) { 428 if (ps) {
430 console.log('Sending proxy auth callback for service', this.id); 429 debug('Sending proxy auth callback for service', this.id);
431 callback(ps.user, ps.password); 430 callback(ps.user, ps.password);
432 } else { 431 } else {
433 console.log('No proxy auth config found for', this.id); 432 debug('No proxy auth config found for', this.id);
434 } 433 }
435 } 434 }
436 }); 435 });
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';
2 2
3import defaultUserAgent from '../helpers/userAgent-helpers'; 3import defaultUserAgent from '../helpers/userAgent-helpers';
4 4
5// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 5const debug = require('../preload-safe-debug')('Ferdium:UserAgent');
6// const debug = require('debug')('Ferdium:UserAgent');
7 6
8export default class UserAgent { 7export default class UserAgent {
9 _willNavigateListener = null; 8 _willNavigateListener = null;
@@ -79,7 +78,7 @@ export default class UserAgent {
79 @action _handleNavigate(url, forwardingHack = false) { 78 @action _handleNavigate(url, forwardingHack = false) {
80 if (url.startsWith('https://accounts.google.com')) { 79 if (url.startsWith('https://accounts.google.com')) {
81 if (!this.chromelessUserAgent) { 80 if (!this.chromelessUserAgent) {
82 console.log('Setting user agent to chromeless for url', url); 81 debug('Setting user agent to chromeless for url', url);
83 this.chromelessUserAgent = true; 82 this.chromelessUserAgent = true;
84 this.webview.userAgent = this.userAgent; 83 this.webview.userAgent = this.userAgent;
85 if (forwardingHack) { 84 if (forwardingHack) {
@@ -87,14 +86,14 @@ export default class UserAgent {
87 } 86 }
88 } 87 }
89 } else if (this.chromelessUserAgent) { 88 } else if (this.chromelessUserAgent) {
90 console.log('Setting user agent to contain chrome for url', url); 89 debug('Setting user agent to contain chrome for url', url);
91 this.chromelessUserAgent = false; 90 this.chromelessUserAgent = false;
92 this.webview.userAgent = this.userAgent; 91 this.webview.userAgent = this.userAgent;
93 } 92 }
94 } 93 }
95 94
96 _addWebviewEvents(webview) { 95 _addWebviewEvents(webview) {
97 console.log('Adding event handlers'); 96 debug('Adding event handlers');
98 97
99 this._willNavigateListener = event => this._handleNavigate(event.url, true); 98 this._willNavigateListener = event => this._handleNavigate(event.url, true);
100 webview.addEventListener('will-navigate', this._willNavigateListener); 99 webview.addEventListener('will-navigate', this._willNavigateListener);
@@ -104,7 +103,7 @@ export default class UserAgent {
104 } 103 }
105 104
106 _removeWebviewEvents(webview) { 105 _removeWebviewEvents(webview) {
107 console.log('Removing event handlers'); 106 debug('Removing event handlers');
108 107
109 webview.removeEventListener('will-navigate', this._willNavigateListener); 108 webview.removeEventListener('will-navigate', this._willNavigateListener);
110 webview.removeEventListener('did-navigate', this._didNavigateListener); 109 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 @@
1/*
2 eslint-disable global-require --
3 This file contains a workaround for situations were global require is problematic.
4*/
5
6/**
7 * Make sure we don't try to load `debug` in the preload script.
8 *
9 * Doing so would trigger the bug https://github.com/electron/electron/issues/31689
10 * because `debug` will try to access `localStorage` to save the log level:
11 * https://www.npmjs.com/package/debug#user-content-browser-support
12 *
13 * We check for the presence of `ipcRenderer`, a render-only electron API,
14 * to detect whether we're in the renderer process.
15 * We serve the user interface from the `file://` origin, so any different origin
16 * must be a preload script.
17 */
18module.exports = function debug(namespace: string): (...params: any[]) => void {
19 if ('ipcRenderer' in require('electron') && window.origin !== 'file://') {
20 // Only output debug messages to the console if debugging is requested.
21 // We don't reimplement the matching algorithm from `debug` and just dump all
22 // messages to the console if some form of `Ferdium` debugging is enabled.
23 if (process.env.DEBUG?.startsWith('Ferdium:')) {
24 return (...params) => console.debug(`[${namespace}]`, ...params);
25 }
26 return () => { };
27 }
28 return require('debug')(namespace);
29}
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 {
29import { openExternalUrl } from '../helpers/url-helpers'; 29import { openExternalUrl } from '../helpers/url-helpers';
30import { sleep } from '../helpers/async-helpers'; 30import { sleep } from '../helpers/async-helpers';
31 31
32// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 32const debug = require('../preload-safe-debug')('Ferdium:AppStore');
33// const debug = require('debug')('Ferdium:AppStore');
34 33
35const mainWindow = getCurrentWindow(); 34const mainWindow = getCurrentWindow();
36 35
@@ -196,7 +195,7 @@ export default class AppStore extends Store {
196 195
197 // Handle deep linking (ferdium://) 196 // Handle deep linking (ferdium://)
198 ipcRenderer.on('navigateFromDeepLink', (event, data) => { 197 ipcRenderer.on('navigateFromDeepLink', (event, data) => {
199 console.log('Navigate from deep link', data); 198 debug('Navigate from deep link', data);
200 let { url } = data; 199 let { url } = data;
201 if (!url) return; 200 if (!url) return;
202 201
@@ -218,28 +217,28 @@ export default class AppStore extends Store {
218 this.isSystemDarkModeEnabled = nativeTheme.shouldUseDarkColors; 217 this.isSystemDarkModeEnabled = nativeTheme.shouldUseDarkColors;
219 218
220 ipcRenderer.on('isWindowFocused', (event, isFocused) => { 219 ipcRenderer.on('isWindowFocused', (event, isFocused) => {
221 console.log('Setting is focused to', isFocused); 220 debug('Setting is focused to', isFocused);
222 this.isFocused = isFocused; 221 this.isFocused = isFocused;
223 }); 222 });
224 223
225 powerMonitor.on('suspend', () => { 224 powerMonitor.on('suspend', () => {
226 console.log('System suspended starting timer'); 225 debug('System suspended starting timer');
227 226
228 this.timeSuspensionStart = moment(); 227 this.timeSuspensionStart = moment();
229 }); 228 });
230 229
231 powerMonitor.on('resume', () => { 230 powerMonitor.on('resume', () => {
232 console.log('System resumed, last suspended on', this.timeSuspensionStart); 231 debug('System resumed, last suspended on', this.timeSuspensionStart);
233 this.actions.service.resetLastPollTimer(); 232 this.actions.service.resetLastPollTimer();
234 233
235 if ( 234 if (
236 this.timeSuspensionStart.add(10, 'm').isBefore(moment()) && 235 this.timeSuspensionStart.add(10, 'm').isBefore(moment()) &&
237 this.stores.settings.app.get('reloadAfterResume') 236 this.stores.settings.app.get('reloadAfterResume')
238 ) { 237 ) {
239 console.log('Reloading services, user info and features'); 238 debug('Reloading services, user info and features');
240 239
241 setInterval(() => { 240 setInterval(() => {
242 console.log('Reload app interval is starting'); 241 debug('Reload app interval is starting');
243 if (this.isOnline) { 242 if (this.isOnline) {
244 window.location.reload(); 243 window.location.reload();
245 } 244 }
@@ -251,7 +250,7 @@ export default class AppStore extends Store {
251 // notifications got stuck after upgrade but forcing a notification 250 // notifications got stuck after upgrade but forcing a notification
252 // via `new Notification` triggered the permission request 251 // via `new Notification` triggered the permission request
253 if (isMac && !localStorage.getItem(CATALINA_NOTIFICATION_HACK_KEY)) { 252 if (isMac && !localStorage.getItem(CATALINA_NOTIFICATION_HACK_KEY)) {
254 console.log('Triggering macOS Catalina notification permission trigger'); 253 debug('Triggering macOS Catalina notification permission trigger');
255 // eslint-disable-next-line no-new 254 // eslint-disable-next-line no-new
256 new window.Notification('Welcome to Ferdium 5', { 255 new window.Notification('Welcome to Ferdium 5', {
257 body: 'Have a wonderful day & happy messaging.', 256 body: 'Have a wonderful day & happy messaging.',
@@ -320,7 +319,7 @@ export default class AppStore extends Store {
320 319
321 const notification = new window.Notification(title, options); 320 const notification = new window.Notification(title, options);
322 321
323 console.log('New notification', title, options); 322 debug('New notification', title, options);
324 323
325 notification.addEventListener('click', () => { 324 notification.addEventListener('click', () => {
326 if (serviceId) { 325 if (serviceId) {
@@ -342,7 +341,7 @@ export default class AppStore extends Store {
342 } 341 }
343 mainWindow.focus(); 342 mainWindow.focus();
344 343
345 console.log('Notification click handler'); 344 debug('Notification click handler');
346 } 345 }
347 }); 346 });
348 } 347 }
@@ -371,10 +370,10 @@ export default class AppStore extends Store {
371 370
372 try { 371 try {
373 if (enable) { 372 if (enable) {
374 console.log('enabling launch on startup', executablePath); 373 debug('enabling launch on startup', executablePath);
375 autoLauncher.enable(); 374 autoLauncher.enable();
376 } else { 375 } else {
377 console.log('disabling launch on startup'); 376 debug('disabling launch on startup');
378 autoLauncher.disable(); 377 autoLauncher.disable();
379 } 378 }
380 } catch (error) { 379 } catch (error) {
@@ -389,7 +388,7 @@ export default class AppStore extends Store {
389 388
390 @action _checkForUpdates() { 389 @action _checkForUpdates() {
391 if (this.isOnline && this.stores.settings.app.automaticUpdates && (isMac || isWindows || process.env.APPIMAGE)) { 390 if (this.isOnline && this.stores.settings.app.automaticUpdates && (isMac || isWindows || process.env.APPIMAGE)) {
392 console.log('_checkForUpdates: sending event to autoUpdate:check'); 391 debug('_checkForUpdates: sending event to autoUpdate:check');
393 this.updateStatus = this.updateStatusTypes.CHECKING; 392 this.updateStatus = this.updateStatusTypes.CHECKING;
394 ipcRenderer.send('autoUpdate', { 393 ipcRenderer.send('autoUpdate', {
395 action: 'check', 394 action: 'check',
@@ -402,7 +401,7 @@ export default class AppStore extends Store {
402 } 401 }
403 402
404 @action _installUpdate() { 403 @action _installUpdate() {
405 console.log('_installUpdate: sending event to autoUpdate:install'); 404 debug('_installUpdate: sending event to autoUpdate:install');
406 ipcRenderer.send('autoUpdate', { 405 ipcRenderer.send('autoUpdate', {
407 action: 'install', 406 action: 'install',
408 }); 407 });
@@ -488,7 +487,7 @@ export default class AppStore extends Store {
488 } 487 }
489 488
490 moment.locale(this.locale); 489 moment.locale(this.locale);
491 console.log(`Set locale to "${this.locale}"`); 490 debug(`Set locale to "${this.locale}"`);
492 } 491 }
493 492
494 _getDefaultLocale() { 493 _getDefaultLocale() {
@@ -542,7 +541,7 @@ export default class AppStore extends Store {
542 this.autoLaunchOnStart = await this._checkAutoStart(); 541 this.autoLaunchOnStart = await this._checkAutoStart();
543 542
544 if (this.stores.settings.all.stats.appStarts === 1) { 543 if (this.stores.settings.all.stats.appStarts === 1) {
545 console.log('Set app to launch on start'); 544 debug('Set app to launch on start');
546 this.actions.app.launchOnStartup({ 545 this.actions.app.launchOnStartup({
547 enable: true, 546 enable: true,
548 }); 547 });
@@ -554,9 +553,9 @@ export default class AppStore extends Store {
554 } 553 }
555 554
556 async _systemDND() { 555 async _systemDND() {
557 console.log('Checking if Do Not Disturb Mode is on'); 556 debug('Checking if Do Not Disturb Mode is on');
558 const dnd = await ipcRenderer.invoke('get-dnd'); 557 const dnd = await ipcRenderer.invoke('get-dnd');
559 console.log('Do not disturb mode is', dnd); 558 debug('Do not disturb mode is', dnd);
560 if ( 559 if (
561 dnd !== this.stores.settings.all.app.isAppMuted && 560 dnd !== this.stores.settings.all.app.isAppMuted &&
562 !this.isSystemMuteOverridden 561 !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';
8import { matchRoute } from '../helpers/routing-helpers'; 8import { matchRoute } from '../helpers/routing-helpers';
9import { asarRecipesPath } from '../helpers/asar-helpers'; 9import { asarRecipesPath } from '../helpers/asar-helpers';
10 10
11// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 11const debug = require('../preload-safe-debug')('Ferdium:RecipeStore');
12// const debug = require('debug')('Ferdium:RecipeStore');
13 12
14export default class RecipesStore extends Store { 13export default class RecipesStore extends Store {
15 @observable allRecipesRequest = new CachedRequest(this.api.recipes, 'all'); 14 @observable allRecipesRequest = new CachedRequest(this.api.recipes, 'all');
@@ -48,7 +47,7 @@ export default class RecipesStore extends Store {
48 return activeRecipe; 47 return activeRecipe;
49 } 48 }
50 49
51 console.log(`Recipe ${match.id} not installed`); 50 debug(`Recipe ${match.id} not installed`);
52 } 51 }
53 52
54 return null; 53 return null;
@@ -79,7 +78,7 @@ export default class RecipesStore extends Store {
79 const recipes = {}; 78 const recipes = {};
80 79
81 // Hackfix, reference this.all to fetch services 80 // Hackfix, reference this.all to fetch services
82 console.log(`Check Recipe updates for ${this.all.map(recipe => recipe.id)}`); 81 debug(`Check Recipe updates for ${this.all.map(recipe => recipe.id)}`);
83 82
84 for (const r of recipeIds) { 83 for (const r of recipeIds) {
85 const recipe = this.one(r); 84 const recipe = this.one(r);
@@ -108,7 +107,7 @@ export default class RecipesStore extends Store {
108 } 107 }
109 108
110 const updates = [...remoteUpdates, ...localUpdates]; 109 const updates = [...remoteUpdates, ...localUpdates];
111 console.log( 110 debug(
112 'Got update information (local, remote):', 111 'Got update information (local, remote):',
113 localUpdates, 112 localUpdates,
114 remoteUpdates, 113 remoteUpdates,
@@ -146,7 +145,7 @@ export default class RecipesStore extends Store {
146 145
147 if (!this.stores.recipes.isInstalled(recipeId)) { 146 if (!this.stores.recipes.isInstalled(recipeId)) {
148 router.push('/settings/recipes'); 147 router.push('/settings/recipes');
149 console.log(`Recipe ${recipeId} is not installed, trying to install it`); 148 debug(`Recipe ${recipeId} is not installed, trying to install it`);
150 149
151 const recipe = await this.installRecipeRequest.execute(recipeId) 150 const recipe = await this.installRecipeRequest.execute(recipeId)
152 ._promise; 151 ._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';
4 4
5import Store from './lib/Store'; 5import Store from './lib/Store';
6 6
7// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 7const debug = require('../preload-safe-debug')('Ferdium:RequestsStore');
8// const debug = require('debug')('Ferdium:RequestsStore');
9 8
10export default class RequestStore extends Store { 9export default class RequestStore extends Store {
11 @observable userInfoRequest; 10 @observable userInfoRequest;
@@ -66,7 +65,7 @@ export default class RequestStore extends Store {
66 } 65 }
67 66
68 this._autoRetry(); 67 this._autoRetry();
69 console.log(`Retry required requests delayed in ${delay / 1000}s`); 68 debug(`Retry required requests delayed in ${delay / 1000}s`);
70 }, delay); 69 }, delay);
71 } 70 }
72 } 71 }
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';
19import { SPELLCHECKER_LOCALES } from '../i18n/languages'; 19import { SPELLCHECKER_LOCALES } from '../i18n/languages';
20import { ferdiumVersion } from '../environment-remote'; 20import { ferdiumVersion } from '../environment-remote';
21 21
22// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 22const debug = require('../preload-safe-debug')('Ferdium:ServiceStore');
23// const debug = require('debug')('Ferdium:ServiceStore');
24 23
25export default class ServicesStore extends Store { 24export default class ServicesStore extends Store {
26 @observable allServicesRequest = new CachedRequest(this.api.services, 'all'); 25 @observable allServicesRequest = new CachedRequest(this.api.services, 'all');
@@ -213,7 +212,7 @@ export default class ServicesStore extends Store {
213 serviceMaintenanceTick = debounce(() => { 212 serviceMaintenanceTick = debounce(() => {
214 this._serviceMaintenance(); 213 this._serviceMaintenance();
215 this.serviceMaintenanceTick(); 214 this.serviceMaintenanceTick();
216 console.log('Service maintenance tick'); 215 debug('Service maintenance tick');
217 }, ms('10s')); 216 }, ms('10s'));
218 217
219 /** 218 /**
@@ -251,7 +250,7 @@ export default class ServicesStore extends Store {
251 // If service did not reply for more than 1m try to reload. 250 // If service did not reply for more than 1m try to reload.
252 if (!service.isActive) { 251 if (!service.isActive) {
253 if (this.stores.app.isOnline && service.lostRecipeReloadAttempt < 3) { 252 if (this.stores.app.isOnline && service.lostRecipeReloadAttempt < 3) {
254 console.log( 253 debug(
255 `Reloading service: ${service.name} (${service.id}). Attempt: ${service.lostRecipeReloadAttempt}`, 254 `Reloading service: ${service.name} (${service.id}). Attempt: ${service.lostRecipeReloadAttempt}`,
256 ); 255 );
257 // service.webview.reload(); 256 // service.webview.reload();
@@ -260,7 +259,7 @@ export default class ServicesStore extends Store {
260 service.lostRecipeConnection = false; 259 service.lostRecipeConnection = false;
261 } 260 }
262 } else { 261 } else {
263 console.log(`Service lost connection: ${service.name} (${service.id}).`); 262 debug(`Service lost connection: ${service.name} (${service.id}).`);
264 service.lostRecipeConnection = true; 263 service.lostRecipeConnection = true;
265 } 264 }
266 } else { 265 } else {
@@ -364,7 +363,7 @@ export default class ServicesStore extends Store {
364 return activeService; 363 return activeService;
365 } 364 }
366 365
367 console.log('Service not available'); 366 debug('Service not available');
368 } 367 }
369 368
370 return null; 369 return null;
@@ -398,9 +397,9 @@ export default class ServicesStore extends Store {
398 skipCleanup = false, 397 skipCleanup = false,
399 }) { 398 }) {
400 if (!this.stores.recipes.isInstalled(recipeId)) { 399 if (!this.stores.recipes.isInstalled(recipeId)) {
401 console.log(`Recipe "${recipeId}" is not installed, installing recipe`); 400 debug(`Recipe "${recipeId}" is not installed, installing recipe`);
402 await this.stores.recipes._install({ recipeId }); 401 await this.stores.recipes._install({ recipeId });
403 console.log(`Recipe "${recipeId}" installed`); 402 debug(`Recipe "${recipeId}" installed`);
404 } 403 }
405 404
406 // set default values for serviceData 405 // set default values for serviceData
@@ -617,7 +616,7 @@ export default class ServicesStore extends Store {
617 if (service) { 616 if (service) {
618 service.isActive = false; 617 service.isActive = false;
619 } else { 618 } else {
620 console.log('No service is active'); 619 debug('No service is active');
621 } 620 }
622 } 621 }
623 622
@@ -660,7 +659,7 @@ export default class ServicesStore extends Store {
660 service.webview = webview; 659 service.webview = webview;
661 660
662 if (!service.isAttached) { 661 if (!service.isAttached) {
663 console.log('Webview is not attached, initializing'); 662 debug('Webview is not attached, initializing');
664 service.initializeWebViewEvents({ 663 service.initializeWebViewEvents({
665 handleIPCMessage: this.actions.service.handleIPCMessage, 664 handleIPCMessage: this.actions.service.handleIPCMessage,
666 openWindow: this.actions.service.openWindow, 665 openWindow: this.actions.service.openWindow,
@@ -709,7 +708,7 @@ export default class ServicesStore extends Store {
709 } 708 }
710 } 709 }
711 } else { 710 } else {
712 console.log('No service is active'); 711 debug('No service is active');
713 } 712 }
714 } else { 713 } else {
715 this.allServicesRequest.invalidate(); 714 this.allServicesRequest.invalidate();
@@ -728,7 +727,7 @@ export default class ServicesStore extends Store {
728 // eslint-disable-next-line default-case 727 // eslint-disable-next-line default-case
729 switch (channel) { 728 switch (channel) {
730 case 'hello': { 729 case 'hello': {
731 console.log('Received hello event from', serviceId); 730 debug('Received hello event from', serviceId);
732 731
733 this._initRecipePolling(service.id); 732 this._initRecipePolling(service.id);
734 this._initializeServiceRecipeInWebview(serviceId); 733 this._initializeServiceRecipeInWebview(serviceId);
@@ -742,7 +741,7 @@ export default class ServicesStore extends Store {
742 break; 741 break;
743 } 742 }
744 case 'message-counts': { 743 case 'message-counts': {
745 console.log(`Received unread message info from '${serviceId}'`, args[0]); 744 debug(`Received unread message info from '${serviceId}'`, args[0]);
746 745
747 this.actions.service.setUnreadMessageCount({ 746 this.actions.service.setUnreadMessageCount({
748 serviceId, 747 serviceId,
@@ -755,7 +754,7 @@ export default class ServicesStore extends Store {
755 break; 754 break;
756 } 755 }
757 case 'active-dialog-title': { 756 case 'active-dialog-title': {
758 console.log(`Received active dialog title from '${serviceId}'`, args[0]); 757 debug(`Received active dialog title from '${serviceId}'`, args[0]);
759 758
760 this.actions.service.setDialogTitle({ 759 this.actions.service.setDialogTitle({
761 serviceId, 760 serviceId,
@@ -920,7 +919,7 @@ export default class ServicesStore extends Store {
920 serviceId: service.id, 919 serviceId: service.id,
921 }); 920 });
922 } else { 921 } else {
923 console.log('No service is active'); 922 debug('No service is active');
924 } 923 }
925 } 924 }
926 925
@@ -1028,7 +1027,7 @@ export default class ServicesStore extends Store {
1028 if (service) { 1027 if (service) {
1029 this._openDevTools({ serviceId: service.id }); 1028 this._openDevTools({ serviceId: service.id });
1030 } else { 1029 } else {
1031 console.log('No service is active'); 1030 debug('No service is active');
1032 } 1031 }
1033 } 1032 }
1034 1033
@@ -1038,7 +1037,7 @@ export default class ServicesStore extends Store {
1038 return; 1037 return;
1039 } 1038 }
1040 1039
1041 console.log(`Hibernate ${service.name}`); 1040 debug(`Hibernate ${service.name}`);
1042 1041
1043 service.isHibernationRequested = true; 1042 service.isHibernationRequested = true;
1044 service.lastHibernated = Date.now(); 1043 service.lastHibernated = Date.now();
@@ -1048,7 +1047,7 @@ export default class ServicesStore extends Store {
1048 const now = Date.now(); 1047 const now = Date.now();
1049 const service = this.one(serviceId); 1048 const service = this.one(serviceId);
1050 const automaticTag = automatic ? ' automatically ' : ' '; 1049 const automaticTag = automatic ? ' automatically ' : ' ';
1051 console.log( 1050 debug(
1052 `Waking up${automaticTag}from service hibernation for ${service.name}`, 1051 `Waking up${automaticTag}from service hibernation for ${service.name}`,
1053 ); 1052 );
1054 1053
@@ -1069,8 +1068,8 @@ export default class ServicesStore extends Store {
1069 // 1068 //
1070 const mainStrategy = this.stores.settings.all.app.hibernationStrategy; 1069 const mainStrategy = this.stores.settings.all.app.hibernationStrategy;
1071 let strategy = this.stores.settings.all.app.wakeUpHibernationStrategy; 1070 let strategy = this.stores.settings.all.app.wakeUpHibernationStrategy;
1072 console.log(`wakeUpHibernationStrategy = ${strategy}`); 1071 debug(`wakeUpHibernationStrategy = ${strategy}`);
1073 console.log(`hibernationStrategy = ${mainStrategy}`); 1072 debug(`hibernationStrategy = ${mainStrategy}`);
1074 if (!strategy || strategy < 1) { 1073 if (!strategy || strategy < 1) {
1075 strategy = this.stores.settings.all.app.hibernationStrategy; 1074 strategy = this.stores.settings.all.app.hibernationStrategy;
1076 } 1075 }
@@ -1082,16 +1081,16 @@ export default class ServicesStore extends Store {
1082 ) { 1081 ) {
1083 // Add 10 additional seconds 50% of the time. 1082 // Add 10 additional seconds 50% of the time.
1084 splay = 10; 1083 splay = 10;
1085 console.log('Added splay'); 1084 debug('Added splay');
1086 } else { 1085 } else {
1087 console.log('skipping splay'); 1086 debug('skipping splay');
1088 } 1087 }
1089 // wake up again in strategy + splay seconds instead of mainStrategy seconds. 1088 // wake up again in strategy + splay seconds instead of mainStrategy seconds.
1090 service.lastUsed = now - ms(`${mainStrategy - (strategy + splay)}s`); 1089 service.lastUsed = now - ms(`${mainStrategy - (strategy + splay)}s`);
1091 } else { 1090 } else {
1092 service.lastUsed = now; 1091 service.lastUsed = now;
1093 } 1092 }
1094 console.log( 1093 debug(
1095 `Setting service.lastUsed to ${service.lastUsed} (${ 1094 `Setting service.lastUsed to ${service.lastUsed} (${
1096 (now - service.lastUsed) / 1000 1095 (now - service.lastUsed) / 1000
1097 }s ago)`, 1096 }s ago)`,
@@ -1101,7 +1100,7 @@ export default class ServicesStore extends Store {
1101 } 1100 }
1102 1101
1103 @action _resetLastPollTimer({ serviceId = null }) { 1102 @action _resetLastPollTimer({ serviceId = null }) {
1104 console.log( 1103 debug(
1105 `Reset last poll timer for ${ 1104 `Reset last poll timer for ${
1106 serviceId ? `service: "${serviceId}"` : 'all services' 1105 serviceId ? `service: "${serviceId}"` : 'all services'
1107 }`, 1106 }`,
@@ -1132,7 +1131,7 @@ export default class ServicesStore extends Store {
1132 service.dialogTitle ? ` - ${service.dialogTitle}` : '' 1131 service.dialogTitle ? ` - ${service.dialogTitle}` : ''
1133 } ${service._webview ? `- ${service._webview.getTitle()}` : ''}`; 1132 } ${service._webview ? `- ${service._webview.getTitle()}` : ''}`;
1134 } else { 1133 } else {
1135 console.log('No service is active'); 1134 debug('No service is active');
1136 } 1135 }
1137 } 1136 }
1138 1137
@@ -1146,7 +1145,7 @@ export default class ServicesStore extends Store {
1146 }, 1145 },
1147 }); 1146 });
1148 } else { 1147 } else {
1149 console.log('No service is active'); 1148 debug('No service is active');
1150 } 1149 }
1151 } 1150 }
1152 1151
@@ -1262,7 +1261,7 @@ export default class ServicesStore extends Store {
1262 this.allDisplayed.findIndex(service => service.isActive) === -1 && 1261 this.allDisplayed.findIndex(service => service.isActive) === -1 &&
1263 this.allDisplayed.length > 0 1262 this.allDisplayed.length > 0
1264 ) { 1263 ) {
1265 console.log('No active service found, setting active service to index 0'); 1264 debug('No active service found, setting active service to index 0');
1266 1265
1267 this._setActive({ serviceId: this.allDisplayed[0].id }); 1266 this._setActive({ serviceId: this.allDisplayed[0].id });
1268 } 1267 }
@@ -1278,7 +1277,7 @@ export default class ServicesStore extends Store {
1278 JSON.stringify(service.shareWithWebview), 1277 JSON.stringify(service.shareWithWebview),
1279 ); 1278 );
1280 1279
1281 console.log('Initialize recipe', service.recipe.id, service.name); 1280 debug('Initialize recipe', service.recipe.id, service.name);
1282 service.webview.send( 1281 service.webview.send(
1283 'initialize-recipe', 1282 'initialize-recipe',
1284 { 1283 {
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';
11import Request from './lib/Request'; 11import Request from './lib/Request';
12import Store from './lib/Store'; 12import Store from './lib/Store';
13 13
14// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 14const debug = require('../preload-safe-debug')('Ferdium:SettingsStore');
15// const debug = require('debug')('Ferdium:SettingsStore');
16 15
17export default class SettingsStore extends Store { 16export default class SettingsStore extends Store {
18 @observable updateAppSettingsRequest = new Request( 17 @observable updateAppSettingsRequest = new Request(
@@ -95,7 +94,7 @@ export default class SettingsStore extends Store {
95 } 94 }
96 }); 95 });
97 } 96 }
98 console.log('Get appSettings resolves', resp.type, resp.data); 97 debug('Get appSettings resolves', resp.type, resp.data);
99 Object.assign(this._fileSystemSettingsCache[resp.type], resp.data); 98 Object.assign(this._fileSystemSettingsCache[resp.type], resp.data);
100 this.loaded = true; 99 this.loaded = true;
101 ipcRenderer.send('initialAppSettings', resp); 100 ipcRenderer.send('initialAppSettings', resp);
@@ -147,10 +146,10 @@ export default class SettingsStore extends Store {
147 @action async _update({ type, data }) { 146 @action async _update({ type, data }) {
148 const appSettings = this.all; 147 const appSettings = this.all;
149 if (!this.fileSystemSettingsTypes.includes(type)) { 148 if (!this.fileSystemSettingsTypes.includes(type)) {
150 console.log('Update settings', type, data, this.all); 149 debug('Update settings', type, data, this.all);
151 localStorage.setItem(type, Object.assign(appSettings[type], data)); 150 localStorage.setItem(type, Object.assign(appSettings[type], data));
152 } else { 151 } else {
153 console.log('Update settings on file system', type, data); 152 debug('Update settings on file system', type, data);
154 ipcRenderer.send('updateAppSettings', { 153 ipcRenderer.send('updateAppSettings', {
155 type, 154 type,
156 data, 155 data,
@@ -201,7 +200,7 @@ export default class SettingsStore extends Store {
201 }); 200 });
202 } 201 }
203 202
204 console.log('Migrated updates settings'); 203 debug('Migrated updates settings');
205 }); 204 });
206 205
207 this._ensureMigrationAndMarkDone('5.6.0-beta.6-settings', () => { 206 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';
10import Request from './lib/Request'; 10import Request from './lib/Request';
11import CachedRequest from './lib/CachedRequest'; 11import CachedRequest from './lib/CachedRequest';
12 12
13// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 13const debug = require('../preload-safe-debug')('Ferdium:UserStore');
14// const debug = require('debug')('Ferdium:UserStore');
15 14
16// TODO: split stores into UserStore and AuthStore 15// TODO: split stores into UserStore and AuthStore
17export default class UserStore extends Store { 16export default class UserStore extends Store {
@@ -395,7 +394,7 @@ export default class UserStore extends Store {
395 } 394 }
396 395
397 if (!this.data.locale) { 396 if (!this.data.locale) {
398 console.log('Migrate "locale" to user data'); 397 debug('Migrate "locale" to user data');
399 this.actions.user.update({ 398 this.actions.user.update({
400 userData: { 399 userData: {
401 locale: this.stores.app.locale, 400 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 @@
1import { ipcRenderer } from 'electron'; 1import { ipcRenderer } from 'electron';
2 2
3// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 3const debug = require('../preload-safe-debug')('Ferdium:Plugin:BadgeHandler');
4// const debug = require('debug')('Ferdium:Plugin:BadgeHandler');
5 4
6export class BadgeHandler { 5export class BadgeHandler {
7 // TODO: Need to extract this into a utility class and reuse outside of the recipes 6 // TODO: Need to extract this into a utility class and reuse outside of the recipes
@@ -27,7 +26,7 @@ export class BadgeHandler {
27 indirect: this.safeParseInt(indirect), 26 indirect: this.safeParseInt(indirect),
28 }; 27 };
29 28
30 console.log('Sending badge count to host: %j', count); 29 debug('Sending badge count to host: %j', count);
31 ipcRenderer.sendToHost('message-counts', count); 30 ipcRenderer.sendToHost('message-counts', count);
32 } 31 }
33} 32}
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 @@
1import { join } from 'path'; 1import { join } from 'path';
2import { pathExistsSync, readFileSync } from 'fs-extra'; 2import { pathExistsSync, readFileSync } from 'fs-extra';
3 3
4// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 4const debug = require('../preload-safe-debug')('Ferdium:DarkMode');
5// const debug = require('debug')('Ferdium:DarkMode');
6 5
7const chars = [...'abcdefghijklmnopqrstuvwxyz']; 6const chars = [...'abcdefghijklmnopqrstuvwxyz'];
8 7
@@ -27,7 +26,7 @@ export function injectDarkModeStyle(recipePath: string) {
27 26
28 document.querySelector('head')?.appendChild(styles); 27 document.querySelector('head')?.appendChild(styles);
29 28
30 console.log('Injected Dark Mode style with ID', ID); 29 debug('Injected Dark Mode style with ID', ID);
31 } 30 }
32} 31}
33 32
@@ -37,7 +36,7 @@ export function removeDarkModeStyle() {
37 if (style) { 36 if (style) {
38 style.remove(); 37 style.remove();
39 38
40 console.log('Removed Dark Mode Style with ID', ID); 39 debug('Removed Dark Mode Style with ID', ID);
41 } 40 }
42} 41}
43 42
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 @@
1import { ipcRenderer } from 'electron'; 1import { ipcRenderer } from 'electron';
2 2
3// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 3const debug = require('../preload-safe-debug')('Ferdium:Plugin:DialogTitleHandler');
4// const debug = require('debug')('Ferdium:Plugin:DialogTitleHandler');
5 4
6export class DialogTitleHandler { 5export class DialogTitleHandler {
7 titleCache: { title: string }; 6 titleCache: { title: string };
@@ -26,7 +25,7 @@ export class DialogTitleHandler {
26 return; 25 return;
27 } 26 }
28 27
29 console.log('Sending active dialog title to host %s', newTitle); 28 debug('Sending active dialog title to host %s', newTitle);
30 ipcRenderer.sendToHost('active-dialog-title', newTitle); 29 ipcRenderer.sendToHost('active-dialog-title', newTitle);
31 30
32 this.titleCache.title = newTitle; 31 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';
2import { BrowserWindow } from '@electron/remote'; 2import { BrowserWindow } from '@electron/remote';
3import { pathExistsSync, readFileSync, existsSync } from 'fs-extra'; 3import { pathExistsSync, readFileSync, existsSync } from 'fs-extra';
4 4
5// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 5const debug = require('../../preload-safe-debug')('Ferdium:Plugin:RecipeWebview');
6// const debug = require('debug')('Ferdium:Plugin:RecipeWebview');
7 6
8class RecipeWebview { 7class RecipeWebview {
9 badgeHandler: any; 8 badgeHandler: any;
@@ -28,7 +27,7 @@ class RecipeWebview {
28 ipcRenderer.on('poll', () => { 27 ipcRenderer.on('poll', () => {
29 this.loopFunc(); 28 this.loopFunc();
30 29
31 console.log('Poll event'); 30 debug('Poll event');
32 31
33 // This event is for checking if the service recipe is still actively 32 // This event is for checking if the service recipe is still actively
34 // communicating with the client 33 // communicating with the client
@@ -110,7 +109,7 @@ class RecipeWebview {
110 109
111 if (head) { 110 if (head) {
112 head.append(styles); 111 head.append(styles);
113 console.log('Append styles', styles); 112 debug('Append styles', styles);
114 } 113 }
115 } 114 }
116 }); 115 });
@@ -122,13 +121,13 @@ class RecipeWebview {
122 if (existsSync(file)) { 121 if (existsSync(file)) {
123 return readFileSync(file, 'utf8'); 122 return readFileSync(file, 'utf8');
124 } 123 }
125 console.log('Script not found', file); 124 debug('Script not found', file);
126 return null; 125 return null;
127 }), 126 }),
128 ).then(scripts => { 127 ).then(scripts => {
129 const scriptsFound = scripts.filter(script => script !== null); 128 const scriptsFound = scripts.filter(script => script !== null);
130 if (scriptsFound.length > 0) { 129 if (scriptsFound.length > 0) {
131 console.log('Inject scripts to main world', scriptsFound); 130 debug('Inject scripts to main world', scriptsFound);
132 ipcRenderer.sendToHost('inject-js-unsafe', ...scriptsFound); 131 ipcRenderer.sendToHost('inject-js-unsafe', ...scriptsFound);
133 } 132 }
134 }); 133 });
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';
2 2
3import { v1 as uuidV1 } from 'uuid'; 3import { v1 as uuidV1 } from 'uuid';
4 4
5// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 5const debug = require('../preload-safe-debug')('Ferdium:Notifications');
6// const debug = require('debug')('Ferdium:Notifications');
7 6
8export class NotificationsHandler { 7export class NotificationsHandler {
9 onNotify = (data: { title: string; options: any; notificationId: string }) => 8 onNotify = (data: { title: string; options: any; notificationId: string }) =>
@@ -11,7 +10,7 @@ export class NotificationsHandler {
11 10
12 displayNotification(title: string, options: any) { 11 displayNotification(title: string, options: any) {
13 return new Promise(resolve => { 12 return new Promise(resolve => {
14 console.log('New notification', title, options); 13 debug('New notification', title, options);
15 14
16 const notificationId = uuidV1(); 15 const notificationId = uuidV1();
17 16
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 {
50 50
51import { DEFAULT_APP_SETTINGS } from '../config'; 51import { DEFAULT_APP_SETTINGS } from '../config';
52 52
53// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 53const debug = require('../preload-safe-debug')('Ferdium:Plugin');
54// const debug = require('debug')('Ferdium:Plugin');
55 54
56const badgeHandler = new BadgeHandler(); 55const badgeHandler = new BadgeHandler();
57 56
@@ -65,7 +64,7 @@ const notificationsHandler = new NotificationsHandler();
65const originalWindowOpen = window.open; 64const originalWindowOpen = window.open;
66 65
67window.open = (url, frameName, features) => { 66window.open = (url, frameName, features) => {
68 console.log('window.open', url, frameName, features); 67 debug('window.open', url, frameName, features);
69 if (!url) { 68 if (!url) {
70 // The service hasn't yet supplied a URL (as used in Skype). 69 // The service hasn't yet supplied a URL (as used in Skype).
71 // Return a new dummy window object and wait for the service to change the properties 70 // Return a new dummy window object and wait for the service to change the properties
@@ -171,12 +170,12 @@ class RecipeController {
171 async initialize() { 170 async initialize() {
172 for (const channel of Object.keys(this.ipcEvents)) { 171 for (const channel of Object.keys(this.ipcEvents)) {
173 ipcRenderer.on(channel, (...args) => { 172 ipcRenderer.on(channel, (...args) => {
174 console.log('Received IPC event for channel', channel, 'with', ...args); 173 debug('Received IPC event for channel', channel, 'with', ...args);
175 this[this.ipcEvents[channel]](...args); 174 this[this.ipcEvents[channel]](...args);
176 }); 175 });
177 } 176 }
178 177
179 console.log('Send "hello" to host'); 178 debug('Send "hello" to host');
180 setTimeout(() => ipcRenderer.sendToHost('hello'), 100); 179 setTimeout(() => ipcRenderer.sendToHost('hello'), 100);
181 180
182 this.spellcheckingProvider = null; 181 this.spellcheckingProvider = null;
@@ -199,9 +198,9 @@ class RecipeController {
199 } 198 }
200 199
201 loadRecipeModule(event, config, recipe) { 200 loadRecipeModule(event, config, recipe) {
202 console.log('loadRecipeModule'); 201 debug('loadRecipeModule');
203 const modulePath = join(recipe.path, 'webview.js'); 202 const modulePath = join(recipe.path, 'webview.js');
204 console.log('module path', modulePath); 203 debug('module path', modulePath);
205 // Delete module from cache 204 // Delete module from cache
206 delete require.cache[require.resolve(modulePath)]; 205 delete require.cache[require.resolve(modulePath)];
207 try { 206 try {
@@ -214,7 +213,7 @@ class RecipeController {
214 if (existsSync(modulePath)) { 213 if (existsSync(modulePath)) {
215 // eslint-disable-next-line import/no-dynamic-require 214 // eslint-disable-next-line import/no-dynamic-require
216 require(modulePath)(this.recipe, { ...config, recipe }); 215 require(modulePath)(this.recipe, { ...config, recipe });
217 console.log('Initialize Recipe', config, recipe); 216 debug('Initialize Recipe', config, recipe);
218 } 217 }
219 218
220 this.settings.service = Object.assign(config, { recipe }); 219 this.settings.service = Object.assign(config, { recipe });
@@ -266,18 +265,18 @@ class RecipeController {
266 } 265 }
267 266
268 update() { 267 update() {
269 console.log('enableSpellchecking', this.settings.app.enableSpellchecking); 268 debug('enableSpellchecking', this.settings.app.enableSpellchecking);
270 console.log('isDarkModeEnabled', this.settings.service.isDarkModeEnabled); 269 debug('isDarkModeEnabled', this.settings.service.isDarkModeEnabled);
271 console.log( 270 debug(
272 'System spellcheckerLanguage', 271 'System spellcheckerLanguage',
273 this.settings.app.spellcheckerLanguage, 272 this.settings.app.spellcheckerLanguage,
274 ); 273 );
275 console.log( 274 debug(
276 'Service spellcheckerLanguage', 275 'Service spellcheckerLanguage',
277 this.settings.service.spellcheckerLanguage, 276 this.settings.service.spellcheckerLanguage,
278 ); 277 );
279 console.log('darkReaderSettigs', this.settings.service.darkReaderSettings); 278 debug('darkReaderSettigs', this.settings.service.darkReaderSettings);
280 console.log('searchEngine', this.settings.app.searchEngine); 279 debug('searchEngine', this.settings.app.searchEngine);
281 280
282 if (this.userscript && this.userscript.internal_setSettings) { 281 if (this.userscript && this.userscript.internal_setSettings) {
283 this.userscript.internal_setSettings(this.settings); 282 this.userscript.internal_setSettings(this.settings);
@@ -285,10 +284,10 @@ class RecipeController {
285 284
286 if (this.settings.app.enableSpellchecking) { 285 if (this.settings.app.enableSpellchecking) {
287 let { spellcheckerLanguage } = this; 286 let { spellcheckerLanguage } = this;
288 console.log(`Setting spellchecker language to ${spellcheckerLanguage}`); 287 debug(`Setting spellchecker language to ${spellcheckerLanguage}`);
289 if (spellcheckerLanguage.includes('automatic')) { 288 if (spellcheckerLanguage.includes('automatic')) {
290 this.automaticLanguageDetection(); 289 this.automaticLanguageDetection();
291 console.log( 290 debug(
292 'Found `automatic` locale, falling back to user locale until detected', 291 'Found `automatic` locale, falling back to user locale until detected',
293 this.settings.app.locale, 292 this.settings.app.locale,
294 ); 293 );
@@ -296,14 +295,14 @@ class RecipeController {
296 } 295 }
297 switchDict(spellcheckerLanguage, this.settings.service.id); 296 switchDict(spellcheckerLanguage, this.settings.service.id);
298 } else { 297 } else {
299 console.log('Disable spellchecker'); 298 debug('Disable spellchecker');
300 } 299 }
301 300
302 if (!this.recipe) { 301 if (!this.recipe) {
303 this.hasUpdatedBeforeRecipeLoaded = true; 302 this.hasUpdatedBeforeRecipeLoaded = true;
304 } 303 }
305 304
306 console.log( 305 debug(
307 'Darkmode enabled?', 306 'Darkmode enabled?',
308 this.settings.service.isDarkModeEnabled, 307 this.settings.service.isDarkModeEnabled,
309 'Dark theme active?', 308 'Dark theme active?',
@@ -323,11 +322,11 @@ class RecipeController {
323 this.settings.service.isDarkModeEnabled && 322 this.settings.service.isDarkModeEnabled &&
324 this.settings.app.isDarkThemeActive !== false 323 this.settings.app.isDarkThemeActive !== false
325 ) { 324 ) {
326 console.log('Enable dark mode'); 325 debug('Enable dark mode');
327 326
328 // Check if recipe has a custom dark mode handler 327 // Check if recipe has a custom dark mode handler
329 if (this.recipe && this.recipe.darkModeHandler) { 328 if (this.recipe && this.recipe.darkModeHandler) {
330 console.log('Using custom dark mode handler'); 329 debug('Using custom dark mode handler');
331 330
332 // Remove other dark mode styles if they were already loaded 331 // Remove other dark mode styles if they were already loaded
333 if (this.hasUpdatedBeforeRecipeLoaded) { 332 if (this.hasUpdatedBeforeRecipeLoaded) {
@@ -338,7 +337,7 @@ class RecipeController {
338 337
339 this.recipe.darkModeHandler(true, handlerConfig); 338 this.recipe.darkModeHandler(true, handlerConfig);
340 } else if (darkModeStyleExists(this.settings.service.recipe.path)) { 339 } else if (darkModeStyleExists(this.settings.service.recipe.path)) {
341 console.log('Injecting darkmode from recipe'); 340 debug('Injecting darkmode from recipe');
342 injectDarkModeStyle(this.settings.service.recipe.path); 341 injectDarkModeStyle(this.settings.service.recipe.path);
343 342
344 // Make sure universal dark mode is disabled 343 // Make sure universal dark mode is disabled
@@ -348,7 +347,7 @@ class RecipeController {
348 this.settings.app.universalDarkMode && 347 this.settings.app.universalDarkMode &&
349 !ignoreList.includes(window.location.host) 348 !ignoreList.includes(window.location.host)
350 ) { 349 ) {
351 console.log('Injecting Dark Reader'); 350 debug('Injecting Dark Reader');
352 351
353 // Use Dark Reader instead 352 // Use Dark Reader instead
354 const { brightness, contrast, sepia } = 353 const { brightness, contrast, sepia } =
@@ -362,8 +361,8 @@ class RecipeController {
362 this.universalDarkModeInjected = true; 361 this.universalDarkModeInjected = true;
363 } 362 }
364 } else { 363 } else {
365 console.log('Remove dark mode'); 364 debug('Remove dark mode');
366 console.log('DarkMode disabled - removing remaining styles'); 365 debug('DarkMode disabled - removing remaining styles');
367 366
368 if (this.recipe && this.recipe.darkModeHandler) { 367 if (this.recipe && this.recipe.darkModeHandler) {
369 // Remove other dark mode styles if they were already loaded 368 // Remove other dark mode styles if they were already loaded
@@ -375,10 +374,10 @@ class RecipeController {
375 374
376 this.recipe.darkModeHandler(false, handlerConfig); 375 this.recipe.darkModeHandler(false, handlerConfig);
377 } else if (isDarkModeStyleInjected()) { 376 } else if (isDarkModeStyleInjected()) {
378 console.log('Removing injected darkmode from recipe'); 377 debug('Removing injected darkmode from recipe');
379 removeDarkModeStyle(); 378 removeDarkModeStyle();
380 } else { 379 } else {
381 console.log('Removing Dark Reader'); 380 debug('Removing Dark Reader');
382 381
383 disableDarkMode(); 382 disableDarkMode();
384 this.universalDarkModeInjected = false; 383 this.universalDarkModeInjected = false;
@@ -406,7 +405,7 @@ class RecipeController {
406 } 405 }
407 406
408 serviceIdEcho(event) { 407 serviceIdEcho(event) {
409 console.log('Received a service echo ping'); 408 debug('Received a service echo ping');
410 event.sender.send('service-id', this.settings.service.id); 409 event.sender.send('service-id', this.settings.service.id);
411 } 410 }
412 411
@@ -428,7 +427,7 @@ class RecipeController {
428 // Force a minimum length to get better detection results 427 // Force a minimum length to get better detection results
429 if (value.length < 25) return; 428 if (value.length < 25) return;
430 429
431 console.log('Detecting language for', value); 430 debug('Detecting language for', value);
432 const locale = await ipcRenderer.invoke('detect-language', { 431 const locale = await ipcRenderer.invoke('detect-language', {
433 sample: value, 432 sample: value,
434 }); 433 });
@@ -438,7 +437,7 @@ class RecipeController {
438 437
439 const spellcheckerLocale = 438 const spellcheckerLocale =
440 getSpellcheckerLocaleByFuzzyIdentifier(locale); 439 getSpellcheckerLocaleByFuzzyIdentifier(locale);
441 console.log( 440 debug(
442 'Language detected reliably, setting spellchecker language to', 441 'Language detected reliably, setting spellchecker language to',
443 spellcheckerLocale, 442 spellcheckerLocale,
444 ); 443 );
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 @@
1// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 1const debug = require('../preload-safe-debug')('Ferdium:Plugin:SessionHandler');
2// const debug = require('debug')('Ferdium:Plugin:SessionHandler');
3 2
4export class SessionHandler { 3export class SessionHandler {
5 async releaseServiceWorkers() { 4 async releaseServiceWorkers() {
@@ -8,10 +7,10 @@ export class SessionHandler {
8 await window.navigator.serviceWorker.getRegistrations(); 7 await window.navigator.serviceWorker.getRegistrations();
9 for (const registration of registrations) { 8 for (const registration of registrations) {
10 registration.unregister(); 9 registration.unregister();
11 console.log('ServiceWorker unregistered'); 10 debug('ServiceWorker unregistered');
12 } 11 }
13 } catch (error) { 12 } catch (error) {
14 console.log(error); 13 debug(error);
15 } 14 }
16 } 15 }
17} 16}
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';
2import { SPELLCHECKER_LOCALES } from '../i18n/languages'; 2import { SPELLCHECKER_LOCALES } from '../i18n/languages';
3import { isMac } from '../environment'; 3import { isMac } from '../environment';
4 4
5// TODO: Go back to 'debug' from 'console.log' when https://github.com/electron/electron/issues/31689 is fixed 5const debug = require('../preload-safe-debug')('Ferdium:spellchecker');
6// const debug = require('debug')('Ferdium:spellchecker');
7 6
8export function getSpellcheckerLocaleByFuzzyIdentifier(identifier: string) { 7export function getSpellcheckerLocaleByFuzzyIdentifier(identifier: string) {
9 const locales = Object.keys(SPELLCHECKER_LOCALES).filter( 8 const locales = Object.keys(SPELLCHECKER_LOCALES).filter(
@@ -17,14 +16,14 @@ export function getSpellcheckerLocaleByFuzzyIdentifier(identifier: string) {
17 16
18export function switchDict(fuzzyLocale: string, serviceId: string) { 17export function switchDict(fuzzyLocale: string, serviceId: string) {
19 if (isMac) { 18 if (isMac) {
20 console.log('Ignoring dictionary changes on macOS'); 19 debug('Ignoring dictionary changes on macOS');
21 return; 20 return;
22 } 21 }
23 22
24 console.log(`Setting spellchecker locale from: ${fuzzyLocale}`); 23 debug(`Setting spellchecker locale from: ${fuzzyLocale}`);
25 const locale = getSpellcheckerLocaleByFuzzyIdentifier(fuzzyLocale); 24 const locale = getSpellcheckerLocaleByFuzzyIdentifier(fuzzyLocale);
26 if (locale) { 25 if (locale) {
27 console.log(`Sending spellcheck locales to host: ${locale}`); 26 debug(`Sending spellcheck locales to host: ${locale}`);
28 ipcRenderer.send('set-spellchecker-locales', { locale, serviceId }); 27 ipcRenderer.send('set-spellchecker-locales', { locale, serviceId });
29 } 28 }
30} 29}