aboutsummaryrefslogtreecommitdiffstats
path: root/src/stores/SettingsStore.ts
blob: 72d6331cb3e2528b1470ab8c683594dba784e485 (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
import { getCurrentWindow } from '@electron/remote';
import { ipcRenderer } from 'electron';
import { action, computed, makeObservable, observable, reaction } from 'mobx';
import localStorage from 'mobx-localstorage';
import type { Stores } from '../@types/stores.types';
import type { Actions } from '../actions/lib/actions';
import type { ApiInterface } from '../api';
import {
  DEFAULT_APP_SETTINGS,
  FILE_SYSTEM_SETTINGS_TYPES,
  LOCAL_SERVER,
} from '../config';
import { hash } from '../helpers/password-helpers';
import TypedStore from './lib/TypedStore';

const debug = require('../preload-safe-debug')('Ferdium:SettingsStore');

export default class SettingsStore extends TypedStore {
  @observable loaded: boolean = false;

  fileSystemSettingsTypes = FILE_SYSTEM_SETTINGS_TYPES;

  @observable _fileSystemSettingsCache = {
    app: DEFAULT_APP_SETTINGS,
    proxy: {},
  };

  constructor(stores: Stores, api: ApiInterface, actions: Actions) {
    super(stores, api, actions);

    makeObservable(this);

    // Register action handlers
    this.actions.settings.update.listen(this._update.bind(this));
    this.actions.settings.remove.listen(this._remove.bind(this));
  }

  async setup(): Promise<void> {
    await this._migrate();

    reaction(
      () => this.all.app.autohideMenuBar,
      () => {
        const currentWindow = getCurrentWindow();
        currentWindow.setMenuBarVisibility(!this.all.app.autohideMenuBar);
        currentWindow.autoHideMenuBar = this.all.app.autohideMenuBar;
      },
    );

    reaction(
      () => this.all.app.server,
      server => {
        if (server === LOCAL_SERVER) {
          ipcRenderer.send('startLocalServer');
        }
      },
      { fireImmediately: true },
    );

    // Inactivity lock timer
    let inactivityTimer;
    getCurrentWindow().on('blur', () => {
      if (
        this.all.app.isLockingFeatureEnabled &&
        this.all.app.inactivityLock !== 0
      ) {
        inactivityTimer = setTimeout(
          () => {
            this.actions.settings.update({
              type: 'app',
              data: {
                locked: true,
              },
            });
          },
          this.all.app.inactivityLock * 1000 * 60,
        );
      }
    });
    getCurrentWindow().on('focus', () => {
      if (inactivityTimer) {
        clearTimeout(inactivityTimer);
      }
    });

    ipcRenderer.on('appSettings', (_, resp) => {
      // Lock on startup if enabled in settings
      if (
        !this.loaded &&
        resp.type === 'app' &&
        resp.data.isLockingFeatureEnabled
      ) {
        process.nextTick(() => {
          if (!this.all.app.locked) {
            this.all.app.locked = true;
          }
        });
      }
      debug('Get appSettings resolves', resp.type, resp.data);
      this.actions.settings.update({
        type: resp.type,
        data: resp.data,
      });
      this.setLoaded();
      ipcRenderer.send('initialAppSettings', resp);
    });

    for (const type of this.fileSystemSettingsTypes) {
      ipcRenderer.send('getAppSettings', type);
    }
  }

  @computed get app() {
    return this._fileSystemSettingsCache.app || DEFAULT_APP_SETTINGS;
  }

  @computed get proxy() {
    return this._fileSystemSettingsCache.proxy || {};
  }

  @computed get service() {
    return (
      localStorage.getItem('service') || {
        activeService: '',
      }
    );
  }

  @computed get stats() {
    return (
      localStorage.getItem('stats') || {
        activeService: '',
      }
    );
  }

  @computed get migration() {
    return localStorage.getItem('migration') || {};
  }

  @computed get all() {
    return {
      app: this.app,
      proxy: this.proxy,
      service: this.service,
      stats: this.stats,
      migration: this.migration,
    };
  }

  @action async setLoaded(): Promise<void> {
    this.loaded = true;
  }

  @action async _update({ type, data }): Promise<void> {
    const appSettings = this.all;
    if (this.fileSystemSettingsTypes.includes(type)) {
      debug('Update settings on file system', type, data);
      ipcRenderer.send('updateAppSettings', {
        type,
        data,
      });

      Object.assign(this._fileSystemSettingsCache[type], data);
    } else {
      debug('Update settings', type, data, this.all);
      localStorage.setItem(type, Object.assign(appSettings[type], data));
    }
  }

  @action async _remove({ type, key }): Promise<void> {
    if (type === 'app') return; // app keys can't be deleted

    const appSettings = this.all[type];
    if (Object.hasOwnProperty.call(appSettings, key)) {
      // eslint-disable-next-line @typescript-eslint/no-dynamic-delete
      delete appSettings[key];

      this.actions.settings.update({
        type,
        data: appSettings,
      });
    }
  }

  // eslint-disable-next-line @typescript-eslint/ban-types
  _ensureMigrationAndMarkDone(migrationName: string, callback: Function): void {
    if (!this.all.migration[migrationName]) {
      callback();

      const data = {};
      data[migrationName] = true;
      this.actions.settings.update({
        type: 'migration',
        data,
      });
    }
  }

  // Helper
  async _migrate(): Promise<void> {
    this._ensureMigrationAndMarkDone('password-hashing', () => {
      if (this.stores.settings.app.lockedPassword !== '') {
        const legacySettings = localStorage.getItem('app') || {};
        this.actions.settings.update({
          type: 'app',
          data: {
            lockedPassword: hash(String(legacySettings.lockedPassword)),
          },
        });
      }

      debug('Migrated password-hashing settings');
    });

    this._ensureMigrationAndMarkDone('5.6.0-beta.6-settings', () => {
      this.actions.settings.update({
        type: 'app',
        data: {
          searchEngine: DEFAULT_APP_SETTINGS.searchEngine,
        },
      });

      debug('Migrated default search engine settings');
    });

    this._ensureMigrationAndMarkDone('user-agent-settings', () => {
      this.actions.settings.update({
        type: 'app',
        data: {
          userAgentPref: DEFAULT_APP_SETTINGS.userAgentPref,
        },
      });

      debug('Migrated default user-agent settings');
    });
  }
}