-
-
Notifications
You must be signed in to change notification settings - Fork 21
/
getConfig.js
263 lines (203 loc) · 11.6 KB
/
getConfig.js
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
const errorHandler = require("./util/errorHandler.js");
const fs = require('fs');
const pfs = require('./util/promisifiedFS');
const os = require('os');
const sendNotification = require("./core/sendNotification.js");
let newSettingsNotifSent = false;
let firstCheckDone = false;
let mainConfigPromise = null;
const postConfigExtensions = (userConfig) => new Promise(async res => {
if(!userConfig.saveLocation) userConfig.saveLocation = require(`path`).join((await pfs.existsSync(require(`path`).join(os.homedir(), `Downloads`)) ? require(`path`).join(os.homedir(), `Downloads`) : os.homedir()), `ezytdl`);
userConfig.strings = require(`./configStrings.json`)
userConfig.descriptions = require(`./configDescriptions.json`);
for(const extension of Object.entries(require(`./core/configExtensions.js`).post)) await extension[1](userConfig);
res(userConfig);
})
const configCache = new Map();
const defaultOpts = {
source: `./defaultConfig.json`,
target: `config.json`,
allowNonexistentRemoval: true,
allowChangedDefaults: true,
labelDefaults: false,
waitForPromise: true,
values: false,
clearConfigCache: true,
}
module.exports = (configObject, opts={}) => {
const useOpts = Object.assign({}, defaultOpts, opts);
console.log(`[CONFIG / ${useOpts.source}-${useOpts.target}] config requested!`, useOpts);
let {
source=`./defaultConfig.json`,
target=`config.json`,
allowNonexistentRemoval=true,
allowChangedDefaults=true,
labelDefaults=false,
waitForPromise=true,
values=false,
clearConfigCache=true,
} = useOpts;
const custom = source != `./defaultConfig.json` && target != `config.json` ? true : false;
const key = `${source}-${target}`;
const extendedKey = JSON.stringify(Object.entries(useOpts).filter(([k]) => typeof defaultOpts[k] != `undefined`).sort((a, b) => a[0] > b[0] ? 1 : -1).reduce((o, [k, v]) => Object.assign(o, { [k]: v }), {}));
if(!configObject && configCache.has(key) && configCache.get(key)[extendedKey]) {
console.log(`[CONFIG / ${key} / ext ${extendedKey.length}] config cached! returning`)
const cached = configCache.get(key)[extendedKey];
if(custom) {
return Promise.resolve(values ? Object.values(cached) : cached);
} else {
const val = postConfigExtensions(cached);
return values ? Object.values(val) : val;
}
} else if(configObject && clearConfigCache) {
console.log(`[config / ${key} / ext ${extendedKey.length}] config object passed! clearing cache...`)
configCache.clear();
} else if(configObject) {
console.log(`[config / ${key} / ext ${extendedKey.length}] config object passed! not clearing cache...`);
} else console.log(`[config / ${key} / ext ${extendedKey.length}] config not cached! creating...`);
const promise = new Promise(async res => {
const started = Date.now();
if(custom && mainConfigPromise && waitForPromise) {
console.log(`[config / ${key} / ext ${extendedKey.length}] waiting for main config to load...`)
await mainConfigPromise;
} else if(custom && mainConfigPromise && !waitForPromise) {
console.log(`[config / ${key} / ext ${extendedKey.length}] main config is loading, but waiting for it is disabled!`)
} else if(custom) {
console.log(`[config / ${key} / ext ${extendedKey.length}] main config already loaded!`)
} else {
console.log(`[config / ${key} / ext ${extendedKey.length}] loading main config...`)
};
console.log(`[config / ${key} / ext ${extendedKey.length}] loading this config... (after ${Date.now() - started}ms)`)
try {
const defaultConfig = Object.assign({}, require(source));
if(!custom) for(const extension of Object.entries(require(`./core/configExtensions.js`).defaults)) await extension[1](defaultConfig);
await pfs.mkdirSync(global.configPath, { recursive: true, failIfExists: false });
let checked = false;
if(!await pfs.existsSync(`${global.configPath}/${target}`)) {
fs.writeFileSync(`${global.configPath}/${target}`, JSON.stringify(defaultConfig, null, 4), { encoding: `utf-8` });
checked = true;
} else {
try {
JSON.parse(await pfs.readFileSync(`${global.configPath}/${target}`));
} catch(e) {
await pfs.unlinkSync(`${global.configPath}/${target}`);
module.exports(configObject);
}
};
const checkKeys = (logPrefix, thisKey, config, defaults, addDefaults, removeNonexistent, allowLabelDefaults) => {
if(removeNonexistent && allowNonexistentRemoval) {
for(const key of Object.keys(config)) {
if(typeof defaults[key] == 'undefined') {
delete config[key];
checked = true;
}
}
}
for(const key of Object.keys(defaults)) {
if(addDefaults && typeof config[key] == `undefined`) {
if(!newSettingsNotifSent && !firstCheckDone && !custom) {
newSettingsNotifSent = true;
sendNotification({
headingText: `New settings!`,
bodyText: `New settings have been added to the config! Please check your settings!`
});
}
config[key] = defaults[key];
checked = true;
};
if(!addDefaults && !config[key]) {
} else {
//console.log(`key`, key, `type`, typeof config[key], `value`, config[key], `default type`, typeof defaults[key], `default value`, defaults[key])
if(!allowChangedDefaults && defaults[key] && defaults[key] != config[key]) {
config[key] = defaults[key];
checked = true;
} else if(defaults[key] && typeof defaults[key] == `object`) {
//console.log(`checking keys for ${key}`)
config[key] = checkKeys(logPrefix + ` > `, thisKey + ` / ` + key, config[key], defaults[key], addDefaults, removeNonexistent);
} else {
if(config[key] && typeof config[key] != typeof defaults[key]) {
if(typeof defaults[key] == `number` && !isNaN(config[key])) config[key] = Number(config[key]);
if(typeof defaults[key] == `boolean` && (config[key] == `true` || config[key] == `false`)) config[key] = config[key] == `true` ? true : false;
//console.log(`type`, typeof config[key], `value`, config[key])
}
if((!typeof config[key] || typeof config[key] == `undefined`) && !addDefaults) {
} else if(typeof config[key] != typeof defaults[key]) {
sendNotification({
type: `warn`,
headingText: `Config key mismatch! (${target}: ${key})`,
bodyText: `The config key "${key}" is missing or is of the wrong type! (Expected: ${typeof defaults[key]}, got: ${config[key] ? typeof config[key] : ``})`
});
//console.log(config[key], defaults[key])
config[key] = defaults[key];
if(addDefaults) checked = true;
}
}
}
};
if(labelDefaults && allowLabelDefaults) {
Object.assign(config, {
_defaults: defaults,
});
}
return config;
}
if(!checked) {
const config = JSON.parse(await pfs.readFileSync(`${global.configPath}/${target}`));
const checkedConfig = checkKeys(`> `, `root config object`, config, defaultConfig, true, true);
if(checked) {
fs.writeFileSync(`${global.configPath}/${target}`, JSON.stringify(checkedConfig, null, 4), { encoding: `utf-8` });
}
};
if(configObject) {
configCache.delete(key);
const config = JSON.parse(await pfs.readFileSync(`${global.configPath}/${target}`));
const checkedConfig = checkKeys(`> `, `updated config object`, configObject, defaultConfig, false, false);
const resultingConfig = Object.assign({}, config, checkedConfig)
if(!custom) for(const verification of Object.entries(require(`./core/configExtensions.js`).verify)) await verification[1](resultingConfig);
fs.writeFileSync(`${global.configPath}/${target}`, JSON.stringify(resultingConfig, null, 4), { encoding: `utf-8` });
if(!custom && configObject.alwaysUseLightIcon != undefined) require(`./core/downloadIcon.js`).set();
};
const value = JSON.parse(await pfs.readFileSync(`${global.configPath}/${target}`));
const userConfig = checkKeys(`> `, `final config object`, value, defaultConfig, false, false, true);
if(!custom) {
firstCheckDone = true;
await postConfigExtensions(userConfig);
if(userConfig.downloadFromClipboard) {
global.downloadFromClipboard = true;
} else {
global.downloadFromClipboard = false;
}
global.lastConfig = userConfig;
require(`./util/getPath`)(`./core/confighooks`, true, null, true).then(path => {
pfs.readdirSync(path).then(files => files.filter(f => f.endsWith(`.js`))).then(files => {
for(const file of files) try {
require(`./core/confighooks/${file}`)(userConfig);
console.log(`ran config hook ${file}`)
} catch(e) {
console.error(`failed running config hook ${file}: ${e}`);
}
})
})
};
const existingKey = (configCache.get(key)), append = {
[extendedKey]: userConfig
}
if(existingKey) {
Object.assign(configCache.get(key), append);
} else {
configCache.set(key, append);
}
console.log(`[config / ${key} / ext ${extendedKey.length}] config cached! (${existingKey ? `updated existing entry for key; now has ${Object.keys(existingKey).length} entries` : `created new entry for key`}) (after ${Date.now() - started}ms)`)
res(values ? Object.values(userConfig) : userConfig);
} catch(e) {
console.error(e);
errorHandler(e)
}
});
if(!custom) {
mainConfigPromise = promise;
promise.then(() => mainConfigPromise == promise ? mainConfigPromise = null : null);
}
return promise;
}
module.exports.cache = configCache;