aboutsummaryrefslogtreecommitdiffstats
path: root/packages/main/src/stores/config/loadConfig.ts
blob: 770d6755c7e55164ac8c6efe319a21f7ae89d1e2 (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
/*
 * Copyright (C)  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 {
  applySnapshot,
  IMSTArray,
  IMSTMap,
  IReferenceType,
  IStateTreeNode,
  IType,
} from 'mobx-state-tree';
import { nanoid } from 'nanoid';
import slug from 'slug';

import GlobalSettings from '../GlobalSettings';
import type Profile from '../Profile';
import type { ProfileSettingsSnapshotIn } from '../ProfileSettings';
import type Service from '../Service';
import type { ServiceSettingsSnapshotIn } from '../ServiceSettings';

import type Config from './Config';
import type ProfileConfig from './ProfileConfig';
import type ServiceConfig from './ServiceConfig';

function generateId(name?: string | undefined): string {
  const nameSlug = typeof name === 'undefined' ? '' : slug(name);
  return `${nameSlug}_${nanoid()}`;
}

function addMissingProfileIds(
  profileConfigs: ProfileConfig[] | undefined,
): [string, ProfileSettingsSnapshotIn][] {
  return (profileConfigs ?? []).map((profileConfig) => {
    const { id, ...settings } = profileConfig;
    return [id === undefined ? generateId(settings.name) : id, settings];
  });
}

function addMissingServiceIdsAndProfiles(
  serviceConfigs: ServiceConfig[] | undefined,
  profiles: [string, ProfileSettingsSnapshotIn][],
): [string, ServiceSettingsSnapshotIn][] {
  return (serviceConfigs ?? []).map((serviceConfig) => {
    const { id, ...settings } = serviceConfig;
    const { name } = settings;
    let { profile: profileId } = settings;
    if (profileId === undefined) {
      profileId = generateId(name);
      profiles.push([profileId, { name }]);
    }
    return [
      id === undefined ? generateId(name) : id,
      { ...settings, profile: profileId },
    ];
  });
}

type TypeWithSettings<C> = IType<
  { id: string; settings: C },
  unknown,
  { settings: IStateTreeNode<IType<C, unknown, unknown>> }
>;

function applySettings<C, D extends TypeWithSettings<C>>(
  current: IMSTArray<IReferenceType<D>>,
  currentById: IMSTMap<D>,
  toApply: [string, C][],
): void {
  const toApplyById = new Map(toApply);
  const toDelete = new Set(currentById.keys());
  toApplyById.forEach((settingsSnapshot, id) => {
    const model = currentById.get(id);
    if (model === undefined) {
      currentById.set(id, {
        id,
        settings: settingsSnapshot,
      });
    } else {
      toDelete.delete(id);
      applySnapshot(model.settings, settingsSnapshot);
    }
  });
  toDelete.forEach((id) => currentById.delete(id));
  current.clear();
  current.push(...toApply.map(([id]) => id));
}

export default function loadConfig(
  target: {
    readonly profiles: IMSTArray<IReferenceType<typeof Profile>>;
    readonly profilesById: IMSTMap<typeof Profile>;
    selectedService: Service | undefined;
    readonly services: IMSTArray<IReferenceType<typeof Service>>;
    readonly servicesById: IMSTMap<typeof Service>;
    readonly settings: GlobalSettings;
  },
  config: Config,
): void {
  const {
    profiles,
    profilesById,
    selectedService,
    services,
    servicesById,
    settings,
  } = target;
  const { id: selectedServiceId } = selectedService ?? { id: undefined };
  const {
    profiles: profilesConfig,
    services: servicesConfig,
    ...settingsToApply
  } = config;
  const profilesToApply = addMissingProfileIds(profilesConfig);
  const servicesToApply = addMissingServiceIdsAndProfiles(
    servicesConfig,
    profilesToApply,
  );
  applySettings(profiles, profilesById, profilesToApply);
  applySettings(services, servicesById, servicesToApply);
  applySnapshot(settings, settingsToApply);
  let newSelectedService: Service | undefined;
  if (selectedServiceId !== undefined) {
    newSelectedService = servicesById.get(selectedServiceId);
  }
  if (newSelectedService === undefined && services.length > 0) {
    [newSelectedService] = services;
  }
  target.selectedService = newSelectedService;
}