aboutsummaryrefslogtreecommitdiffstats
path: root/packages/main/src/stores/Config.ts
blob: eb536355fa7b6ffe4f778c28d267989da9f40a58 (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
/*
 * Copyright (C)  2021-2022 Kristóf Marussy <kristof@marussy.com>
 *
 * This file is part of Sophie.
 *
 * Sophie is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, version 3.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 *
 * SPDX-License-Identifier: AGPL-3.0-only
 */

import { debounce } from 'lodash';
import {
  applySnapshot,
  flow,
  getSnapshot,
  IDisposer,
  Instance,
  onSnapshot,
} from 'mobx-state-tree';
import {
  config as originalConfig,
  ConfigSnapshotIn,
  ConfigSnapshotOut,
  ThemeSource,
} from '@sophie/shared';

import { CONFIG_DEBOUNCE_TIME, ReadConfigResult } from '../services/ConfigPersistence';
import { getEnv } from '../services/MainEnv';

export const config = originalConfig.actions((self) => ({
  setThemeSource(mode: ThemeSource) {
    self.themeSource = mode;
  },
})).actions((self) => {
  let lastSnapshotOnDisk: ConfigSnapshotOut | null = null;
  let writingConfig = false;
  let configMtime: Date | null = null;
  let onSnapshotDisposer: IDisposer | null = null;
  let watcherDisposer: IDisposer | null = null;

  function dispose() {
    onSnapshotDisposer?.();
    watcherDisposer?.();
  }

  const actions: {
    beforeDetach(): void,
    readConfig(): Promise<boolean>;
    writeConfig(): Promise<void>;
    initConfig(): Promise<void>;
  } = {
    beforeDetach() {
      dispose();
    },
    readConfig: flow(function*() {
      const result: ReadConfigResult = yield getEnv(self).configPersistence.readConfig();
      if (result.found) {
        try {
          applySnapshot(self, result.data);
          lastSnapshotOnDisk = getSnapshot(self);
          console.log('Loaded config');
        } catch (err) {
          console.error('Failed to read config', result.data, err);
        }
      }
      return result.found;
    }),
    writeConfig: flow(function*() {
      const snapshot = getSnapshot(self);
      writingConfig = true;
      try {
        configMtime = yield getEnv(self).configPersistence.writeConfig(snapshot);
        lastSnapshotOnDisk = snapshot;
        console.log('Wrote config');
      } finally {
        writingConfig = false;
      }
    }),
    initConfig: flow(function*() {
      dispose();
      const foundConfig: boolean = yield actions.readConfig();
      if (!foundConfig) {
        console.log('Creating new config file');
        try {
          yield actions.writeConfig();
        } catch (err) {
          console.error('Failed to initialize config');
        }
      }
      onSnapshotDisposer = onSnapshot(self, debounce((snapshot) => {
        // We can compare snapshots by reference, since it is only recreated on store changes.
        if (lastSnapshotOnDisk !== snapshot) {
          actions.writeConfig().catch((err) => {
            console.log('Failed to write config on config change', err);
          })
        }
      }, CONFIG_DEBOUNCE_TIME));
      watcherDisposer = getEnv(self).configPersistence.watchConfig(async (mtime) => {
        if (!writingConfig && (configMtime === null || mtime > configMtime)) {
          await actions.readConfig();
        }
      });
    }),
  };
  return actions;
});

export interface Config extends Instance<typeof config> {}

export type { ConfigSnapshotIn, ConfigSnapshotOut };