aboutsummaryrefslogtreecommitdiffstats
path: root/packages/main/src/controllers/ConfigController.ts
blob: a28746c527966431141cc283386775c795f56391 (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
/*
 * 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,
  getSnapshot,
  IDisposer,
  onSnapshot,
} from 'mobx-state-tree';

import type { ConfigPersistenceService } from '../services/ConfigPersistenceService';
import type { Config, ConfigSnapshotOut } from '../stores/Config';

export class ConfigController {
  static inject = ['configPersistenceService', 'configDebounceTime'] as const;

  private config: Config | null = null;

  private onSnapshotDisposer: IDisposer | null = null;

  private lastSnapshotOnDisk: ConfigSnapshotOut | null = null;

  private writingConfig: boolean = false;

  constructor(
    private readonly persistenceService: ConfigPersistenceService,
    private readonly debounceTime: number,
  ) {
  }

  async initConfig(config: Config): Promise<void> {
    this.config = config;

    const foundConfig: boolean = await this.readConfig();
    if (!foundConfig) {
      console.log('Creating new config file');
      try {
        await this.writeConfig();
      } catch (err) {
        console.error('Failed to initialize config');
      }
    }

    this.onSnapshotDisposer = onSnapshot(this.config, debounce((snapshot) => {
      // We can compare snapshots by reference, since it is only recreated on store changes.
      if (this.lastSnapshotOnDisk !== snapshot) {
        this.writeConfig().catch((err) => {
          console.log('Failed to write config on config change', err);
        })
      }
    }, this.debounceTime));

    this.persistenceService.watchConfig(async () => {
      if (!this.writingConfig) {
        await this.readConfig();
      }
    }, this.debounceTime);
  }

  private async readConfig(): Promise<boolean> {
    const result = await this.persistenceService.readConfig();
    if (result.found) {
      try {
        applySnapshot(this.config!, result.data);
        this.lastSnapshotOnDisk = getSnapshot(this.config!);
        console.log('Loaded config');
      } catch (err) {
        console.error('Failed to read config', result.data, err);
      }
    }
    return result.found;
  }

  private async writeConfig(): Promise<void> {
    const snapshot = getSnapshot(this.config!);
    this.writingConfig = true;
    try {
      await this.persistenceService.writeConfig(snapshot);
      this.lastSnapshotOnDisk = snapshot;
      console.log('Wrote config');
    } finally {
      this.writingConfig = false;
    }
  }

  dispose(): void {
    this.onSnapshotDisposer?.();
  }
}