aboutsummaryrefslogtreecommitdiffstats
path: root/src/stores/AppStore.js
blob: 1d706f1ef8866ce471b5ab3ffe5eeb021e429bee (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
import { ipcRenderer, shell } from 'electron';
import {
  app,
  screen,
  powerMonitor,
  nativeTheme,
  getCurrentWindow,
  process as remoteProcess,
} from '@electron/remote';
import { action, computed, observable } from 'mobx';
import moment from 'moment';
import AutoLaunch from 'auto-launch';
import ms from 'ms';
import { URL } from 'url';
import { readJsonSync } from 'fs-extra';

import Store from './lib/Store';
import Request from './lib/Request';
import { CHECK_INTERVAL } from '../config';
import {
  DEFAULT_APP_SETTINGS,
  isMac,
  ferdiVersion,
  electronVersion,
  osRelease,
  userDataPath,
} from '../environment';
import locales from '../i18n/translations';
import { onVisibilityChange } from '../helpers/visibility-helper';
import { getLocale } from '../helpers/i18n-helpers';

import {
  getServiceIdsFromPartitions,
  removeServicePartitionDirectory,
} from '../helpers/service-helpers';
import { isValidExternalURL } from '../helpers/url-helpers';
import { sleep } from '../helpers/async-helpers';

const debug = require('debug')('Ferdi:AppStore');

const mainWindow = getCurrentWindow();

const defaultLocale = DEFAULT_APP_SETTINGS.locale;

const executablePath = isMac ? remoteProcess.execPath : process.execPath;
const autoLauncher = new AutoLaunch({
  name: 'Ferdi',
  path: executablePath,
});

const CATALINA_NOTIFICATION_HACK_KEY = '_temp_askedForCatalinaNotificationPermissions';

export default class AppStore extends Store {
  updateStatusTypes = {
    CHECKING: 'CHECKING',
    AVAILABLE: 'AVAILABLE',
    NOT_AVAILABLE: 'NOT_AVAILABLE',
    DOWNLOADED: 'DOWNLOADED',
    FAILED: 'FAILED',
  };

  @observable healthCheckRequest = new Request(this.api.app, 'health');

  @observable getAppCacheSizeRequest = new Request(
    this.api.local,
    'getAppCacheSize',
  );

  @observable clearAppCacheRequest = new Request(this.api.local, 'clearCache');

  @observable autoLaunchOnStart = true;

  @observable isOnline = navigator.onLine;

  @observable authRequestFailed = false;

  @observable timeSuspensionStart = moment();

  @observable timeOfflineStart;

  @observable updateStatus = null;

  @observable locale = defaultLocale;

  @observable isSystemMuteOverridden = false;

  @observable isSystemDarkModeEnabled = false;

  @observable isClearingAllCache = false;

  @observable isFullScreen = mainWindow.isFullScreen();

  @observable isFocused = true;

  @observable nextAppReleaseVersion = null;

  dictionaries = [];

  fetchDataInterval = null;

  constructor(...args) {
    super(...args);

    // Register action handlers
    this.actions.app.notify.listen(this._notify.bind(this));
    this.actions.app.setBadge.listen(this._setBadge.bind(this));
    this.actions.app.launchOnStartup.listen(this._launchOnStartup.bind(this));
    this.actions.app.openExternalUrl.listen(this._openExternalUrl.bind(this));
    this.actions.app.checkForUpdates.listen(this._checkForUpdates.bind(this));
    this.actions.app.installUpdate.listen(this._installUpdate.bind(this));
    this.actions.app.resetUpdateStatus.listen(
      this._resetUpdateStatus.bind(this),
    );
    this.actions.app.healthCheck.listen(this._healthCheck.bind(this));
    this.actions.app.muteApp.listen(this._muteApp.bind(this));
    this.actions.app.toggleMuteApp.listen(this._toggleMuteApp.bind(this));
    this.actions.app.clearAllCache.listen(this._clearAllCache.bind(this));

    this.registerReactions([
      this._offlineCheck.bind(this),
      this._setLocale.bind(this),
      this._muteAppHandler.bind(this),
      this._handleFullScreen.bind(this),
      this._handleLogout.bind(this),
    ]);
  }

  async setup() {
    this._appStartsCounter();
    // Focus the active service
    window.addEventListener('focus', this.actions.service.focusActiveService);

    // Online/Offline handling
    window.addEventListener('online', () => {
      this.isOnline = true;
    });
    window.addEventListener('offline', () => {
      this.isOnline = false;
    });

    mainWindow.on('enter-full-screen', () => {
      this.isFullScreen = true;
    });
    mainWindow.on('leave-full-screen', () => {
      this.isFullScreen = false;
    });

    this.isOnline = navigator.onLine;

    // Check if Ferdi should launch on start
    // Needs to be delayed a bit
    this._autoStart();

    // Check if system is muted
    // There are no events to subscribe so we need to poll everey 5s
    this._systemDND();
    setInterval(() => this._systemDND(), ms('5s'));

    this.fetchDataInterval = setInterval(() => {
      this.stores.user.getUserInfoRequest.invalidate({
        immediately: true,
      });
      this.stores.features.featuresRequest.invalidate({
        immediately: true,
      });
      this.stores.news.latestNewsRequest.invalidate({
        immediately: true,
      });
    }, ms('60m'));

    // Check for updates once every 4 hours
    setInterval(() => this._checkForUpdates(), CHECK_INTERVAL);
    // Check for an update in 30s (need a delay to prevent Squirrel Installer lock file issues)
    setTimeout(() => this._checkForUpdates(), ms('30s'));
    ipcRenderer.on('autoUpdate', (event, data) => {
      if (data.available) {
        this.updateStatus = this.updateStatusTypes.AVAILABLE;
        this.nextAppReleaseVersion = data.version;
        if (isMac) {
          app.dock.bounce();
        }
      }

      if (data.available !== undefined && !data.available) {
        this.updateStatus = this.updateStatusTypes.NOT_AVAILABLE;
      }

      if (data.downloaded) {
        this.updateStatus = this.updateStatusTypes.DOWNLOADED;
        if (isMac) {
          app.dock.bounce();
        }
      }

      if (data.error) {
        this.updateStatus = this.updateStatusTypes.FAILED;
      }
    });

    // Handle deep linking (ferdi://)
    ipcRenderer.on('navigateFromDeepLink', (event, data) => {
      debug('Navigate from deep link', data);
      let { url } = data;
      if (!url) return;

      url = url.replace(/\/$/, '');

      this.stores.router.push(url);
    });

    ipcRenderer.on('muteApp', () => {
      this._toggleMuteApp();
    });

    this.locale = this._getDefaultLocale();

    setTimeout(() => {
      this._healthCheck();
    }, 1000);

    this.isSystemDarkModeEnabled = nativeTheme.shouldUseDarkColors;

    onVisibilityChange((isVisible) => {
      this.isFocused = isVisible;

      debug('Window is visible/focused', isVisible);
    });

    powerMonitor.on('suspend', () => {
      debug('System suspended starting timer');

      this.timeSuspensionStart = moment();
    });

    powerMonitor.on('resume', () => {
      debug('System resumed, last suspended on', this.timeSuspensionStart);
      this.actions.service.resetLastPollTimer();

      if (
        this.timeSuspensionStart.add(10, 'm').isBefore(moment())
        && this.stores.settings.app.get('reloadAfterResume')
      ) {
        debug('Reloading services, user info and features');

        setInterval(() => {
          debug('Reload app interval is starting');
          if (this.isOnline) {
            window.location.reload();
          }
        }, ms('2s'));
      }
    });

    // macOS catalina notifications hack
    // notifications got stuck after upgrade but forcing a notification
    // via `new Notification` triggered the permission request
    if (isMac) {
      if (!localStorage.getItem(CATALINA_NOTIFICATION_HACK_KEY)) {
        debug('Triggering macOS Catalina notification permission trigger');
        // eslint-disable-next-line no-new
        new window.Notification('Welcome to Ferdi 5', {
          body: 'Have a wonderful day & happy messaging.',
        });

        localStorage.setItem(CATALINA_NOTIFICATION_HACK_KEY, true);
      }
    }
  }

  @computed get cacheSize() {
    return this.getAppCacheSizeRequest.execute().result;
  }

  @computed get debugInfo() {
    const settings = JSON.parse(JSON.stringify(this.stores.settings.app));
    settings.lockedPassword = '******';

    return {
      host: {
        platform: process.platform,
        release: osRelease,
        screens: screen.getAllDisplays(),
      },
      ferdi: {
        version: ferdiVersion,
        electron: electronVersion,
        installedRecipes: this.stores.recipes.all.map((recipe) => ({
          id: recipe.id,
          version: recipe.version,
        })),
        devRecipes: this.stores.recipePreviews.dev.map((recipe) => ({
          id: recipe.id,
          version: recipe.version,
        })),
        services: this.stores.services.all.map((service) => ({
          id: service.id,
          recipe: service.recipe.id,
          isAttached: service.isAttached,
          isActive: service.isActive,
          isEnabled: service.isEnabled,
          isHibernating: service.isHibernating,
          hasCrashed: service.hasCrashed,
          isDarkModeEnabled: service.isDarkModeEnabled,
        })),
        messages: this.stores.globalError.messages,
        workspaces: this.stores.workspaces.workspaces.map((workspace) => ({
          id: workspace.id,
          services: workspace.services,
        })),
        windowSettings: readJsonSync(userDataPath('window-state.json')),
        settings,
        features: this.stores.features.features,
        user: this.stores.user.data.id,
      },
    };
  }

  // Actions
  @action _notify({
    title, options, notificationId, serviceId = null,
  }) {
    if (this.stores.settings.all.app.isAppMuted) return;

    // TODO: is there a simple way to use blobs for notifications without storing them on disk?
    if (options.icon && options.icon.startsWith('blob:')) {
      delete options.icon;
    }

    const notification = new window.Notification(title, options);

    debug('New notification', title, options);

    notification.onclick = () => {
      if (serviceId) {
        this.actions.service.sendIPCMessage({
          channel: `notification-onclick:${notificationId}`,
          args: {},
          serviceId,
        });

        this.actions.service.setActive({
          serviceId,
        });
        if (!app.mainWindow.isVisible()) {
          mainWindow.show();
        }
        if (app.mainWindow.isMinimized()) {
          mainWindow.restore();
        }
        mainWindow.focus();

        debug('Notification click handler');
      }
    };
  }

  @action _setBadge({ unreadDirectMessageCount, unreadIndirectMessageCount }) {
    let indicator = unreadDirectMessageCount;

    if (indicator === 0 && unreadIndirectMessageCount !== 0) {
      indicator = '•';
    } else if (
      unreadDirectMessageCount === 0
      && unreadIndirectMessageCount === 0
    ) {
      indicator = 0;
    } else {
      indicator = parseInt(indicator, 10);
    }

    ipcRenderer.send('updateAppIndicator', {
      indicator,
    });
  }

  @action _launchOnStartup({ enable }) {
    this.autoLaunchOnStart = enable;

    try {
      if (enable) {
        debug('enabling launch on startup', executablePath);
        autoLauncher.enable();
      } else {
        debug('disabling launch on startup');
        autoLauncher.disable();
      }
    } catch (err) {
      console.warn(err);
    }
  }

  @action _openExternalUrl({ url }) {
    const parsedUrl = new URL(url);
    debug('open external url', parsedUrl);

    if (isValidExternalURL(url)) {
      shell.openExternal(url);
    }
  }

  @action _checkForUpdates() {
    if (this.isOnline) {
      debug('_checkForUpdates: sending event to autoUpdate:check');
      this.updateStatus = this.updateStatusTypes.CHECKING;
      ipcRenderer.send('autoUpdate', {
        action: 'check',
      });

      this.actions.recipe.update();
    }
  }

  @action _installUpdate() {
    debug('_installUpdate: sending event to autoUpdate:install');
    ipcRenderer.send('autoUpdate', {
      action: 'install',
    });
  }

  @action _resetUpdateStatus() {
    this.updateStatus = null;
  }

  @action _healthCheck() {
    this.healthCheckRequest.execute();
  }

  @action _muteApp({ isMuted, overrideSystemMute = true }) {
    this.isSystemMuteOverridden = overrideSystemMute;
    this.actions.settings.update({
      type: 'app',
      data: {
        isAppMuted: isMuted,
      },
    });
  }

  @action _toggleMuteApp() {
    this._muteApp({
      isMuted: !this.stores.settings.all.app.isAppMuted,
    });
  }

  @action async _clearAllCache() {
    this.isClearingAllCache = true;
    const clearAppCache = this.clearAppCacheRequest.execute();
    const allServiceIds = await getServiceIdsFromPartitions();
    const allOrphanedServiceIds = allServiceIds.filter(
      (id) => !this.stores.services.all.find(
        (s) => id.replace('service-', '') === s.id,
      ),
    );

    try {
      await Promise.all(
        allOrphanedServiceIds.map((id) => removeServicePartitionDirectory(id)),
      );
    } catch (ex) {
      console.log('Error while deleting service partition directory - ', ex);
    }
    await Promise.all(
      this.stores.services.all.map((s) => this.actions.service.clearCache({
        serviceId: s.id,
      })),
    );

    await clearAppCache._promise;

    await sleep(ms('1s'));

    this.getAppCacheSizeRequest.execute();

    this.isClearingAllCache = false;
  }

  // Reactions
  _offlineCheck() {
    if (!this.isOnline) {
      this.timeOfflineStart = moment();
    } else {
      const deltaTime = moment().diff(this.timeOfflineStart);

      if (deltaTime > ms('30m')) {
        this.actions.service.reloadAll();
      }
    }
  }

  _setLocale() {
    let locale;
    if (this.stores.user.isLoggedIn) {
      locale = this.stores.user.data.locale;
    }

    if (
      locale
      && Object.prototype.hasOwnProperty.call(locales, locale)
      && locale !== this.locale
    ) {
      this.locale = locale;
    } else if (!locale) {
      this.locale = this._getDefaultLocale();
    }

    moment.locale(this.locale);

    debug(`Set locale to "${this.locale}"`);
  }

  _getDefaultLocale() {
    return getLocale({
      locale: app.getLocale(),
      locales,
      defaultLocale,
      fallbackLocale: DEFAULT_APP_SETTINGS.fallbackLocale,
    });
  }

  _muteAppHandler() {
    const { showMessageBadgesEvenWhenMuted } = this.stores.ui;

    if (!showMessageBadgesEvenWhenMuted) {
      this.actions.app.setBadge({
        unreadDirectMessageCount: 0,
        unreadIndirectMessageCount: 0,
      });
    }
  }

  _handleFullScreen() {
    const body = document.querySelector('body');

    if (this.isFullScreen) {
      body.classList.add('isFullScreen');
    } else {
      body.classList.remove('isFullScreen');
    }
  }

  _handleLogout() {
    if (!this.stores.user.isLoggedIn) {
      clearInterval(this.fetchDataInterval);
    }
  }

  // Helpers
  _appStartsCounter() {
    this.actions.settings.update({
      type: 'stats',
      data: {
        appStarts: (this.stores.settings.all.stats.appStarts || 0) + 1,
      },
    });
  }

  async _autoStart() {
    this.autoLaunchOnStart = await this._checkAutoStart();

    if (this.stores.settings.all.stats.appStarts === 1) {
      debug('Set app to launch on start');
      this.actions.app.launchOnStartup({
        enable: true,
      });
    }
  }

  async _checkAutoStart() {
    return autoLauncher.isEnabled() || false;
  }

  async _systemDND() {
    debug('Checking if Do Not Disturb Mode is on');
    const dnd = await ipcRenderer.invoke('get-dnd');
    debug('Do not disturb mode is', dnd);
    // ipcRenderer.on('autoUpdate', (event, data) => {
    if (
      dnd !== this.stores.settings.all.app.isAppMuted
      && !this.isSystemMuteOverridden
    ) {
      this.actions.app.muteApp({
        isMuted: dnd,
        overrideSystemMute: false,
      });
    }
  }
}