Repository navigation
Expand file tree
/
Copy pathcfg.js
More file actions
301 lines (256 loc) · 8.86 KB
/
Copy pathcfg.js
File metadata and controls
301 lines (256 loc) · 8.86 KB
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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
const fs = require("fs");
const path = require("path");
const Ajv = require("ajv");
const schema = require("./data/cfg.schema.json");
const cliOpts = require("./cliOpts");
/** @type {ModmailConfig} */
let config = {};
// Auto-detected config files, in priority order
const configFilesToSearch = [
"config.ini",
"config.json",
"config.json5",
"config.js",
// Possible config files when file extensions are hidden
"config.ini.ini",
"config.ini.txt",
"config.json.json",
"config.json.txt",
"config.json.ini",
];
let configFileToLoad;
const requestedConfigFile = cliOpts.config || cliOpts.c; // CLI option --config/-c
if (requestedConfigFile) {
try {
// Config files specified with --config/-c are loaded from cwd
fs.accessSync(requestedConfigFile);
configFileToLoad = requestedConfigFile;
} catch (e) {
if (e.code === "ENOENT") {
console.error(`Specified config file was not found: ${requestedConfigFile}`);
} else {
console.error(`Error reading specified config file ${requestedConfigFile}: ${e.message}`);
}
process.exit(1);
}
} else {
for (const configFile of configFilesToSearch) {
try {
// Auto-detected config files are always loaded from the bot's folder, even if the cwd differs
const relativePath = path.relative(process.cwd(), path.resolve(__dirname, "..", configFile));
fs.accessSync(relativePath);
configFileToLoad = relativePath;
break;
} catch (e) {}
}
}
// Load config values from a config file (if any)
if (configFileToLoad) {
const srcRelativePath = path.resolve(__dirname, process.cwd(), configFileToLoad);
console.log(`Loading configuration from ${configFileToLoad}...`);
try {
if (configFileToLoad.endsWith(".js")) {
config = require(srcRelativePath);
} else {
const raw = fs.readFileSync(configFileToLoad, {encoding: "utf8"});
if (configFileToLoad.endsWith(".ini") || configFileToLoad.endsWith(".ini.txt")) {
config = require("ini").decode(raw);
} else {
config = require("json5").parse(raw);
}
}
} catch (e) {
throw new Error(`Error reading config file! The error given was: ${e.message}`);
}
}
// Set dynamic default values which can't be set in the schema directly
config.dbDir = path.join(__dirname, "..", "db");
config.logDir = path.join(__dirname, "..", "logs"); // Only used for migrating data from older Modmail versions
// Load config values from environment variables
require("dotenv").config();
const envKeyPrefix = "MM_";
let loadedEnvValues = 0;
for (const [key, value] of Object.entries(process.env)) {
if (! key.startsWith(envKeyPrefix)) continue;
// MM_CLOSE_MESSAGE -> closeMessage
// MM_COMMAND_ALIASES__MV => commandAliases.mv
const configKey = key.slice(envKeyPrefix.length)
.toLowerCase()
.replace(/([a-z])_([a-z])/g, (m, m1, m2) => `${m1}${m2.toUpperCase()}`)
.replace("__", ".");
config[configKey] = value.includes("||")
? value.split("||")
: value;
loadedEnvValues++;
}
if (process.env.PORT && ! process.env.MM_PORT) {
// Special case: allow common "PORT" environment variable without prefix
config.port = process.env.PORT;
loadedEnvValues++;
}
if (loadedEnvValues > 0) {
console.log(`Loaded ${loadedEnvValues} ${loadedEnvValues === 1 ? "value" : "values"} from environment variables`);
}
// Convert config keys with periods to objects
// E.g. commandAliases.mv -> commandAliases: { mv: ... }
for (const [key, value] of Object.entries(config)) {
if (! key.includes(".")) continue;
const keys = key.split(".");
let cursor = config;
for (let i = 0; i < keys.length; i++) {
if (i === keys.length - 1) {
cursor[keys[i]] = value;
} else {
cursor[keys[i]] = cursor[keys[i]] || {};
cursor = cursor[keys[i]];
}
}
delete config[key];
}
// mainGuildId => mainServerId
// mailGuildId => inboxServerId
if (config.mainGuildId && ! config.mainServerId) {
config.mainServerId = config.mainGuildId;
}
if (config.mailGuildId && ! config.inboxServerId) {
config.inboxServerId = config.mailGuildId;
}
if (! config.dbType) {
config.dbType = "sqlite";
}
if (! config.sqliteOptions) {
config.sqliteOptions = {
filename: path.resolve(__dirname, "..", "db", "data.sqlite"),
};
}
if (! config.logOptions) {
config.logOptions = {};
}
config.categoryAutomation = config.categoryAutomation || {};
// categoryAutomation.newThreadFromGuild => categoryAutomation.newThreadFromServer
if (config.categoryAutomation && config.categoryAutomation.newThreadFromGuild && ! config.categoryAutomation.newThreadFromServer) {
config.categoryAutomation.newThreadFromServer = config.categoryAutomation.newThreadFromGuild;
}
// guildGreetings => serverGreetings
if (config.guildGreetings && ! config.serverGreetings) {
config.serverGreetings = config.guildGreetings;
}
// Move greetingMessage/greetingAttachment to the serverGreetings object internally
// Or, in other words, if greetingMessage and/or greetingAttachment is set, it is applied for all servers that don't
// already have something set up in serverGreetings. This retains backwards compatibility while allowing you to override
// greetings for specific servers in serverGreetings.
config.serverGreetings = config.serverGreetings || {};
if (config.greetingMessage || config.greetingAttachment) {
for (const guildId of config.mainServerId) {
if (config.serverGreetings[guildId]) continue;
config.serverGreetings[guildId] = {
message: config.greetingMessage,
attachment: config.greetingAttachment
};
}
}
// newThreadCategoryId is syntactic sugar for categoryAutomation.newThread
if (config.newThreadCategoryId) {
config.categoryAutomation = config.categoryAutomation || {};
config.categoryAutomation.newThread = config.newThreadCategoryId;
delete config.newThreadCategoryId;
}
// Delete empty string options (i.e. "option=" without a value in config.ini)
for (const [key, value] of Object.entries(config)) {
if (value === "") {
delete config[key];
}
}
// Validate config and assign defaults (if missing)
const ajv = new Ajv({
useDefaults: true,
coerceTypes: "array",
allowUnionTypes: true,
});
/**
* @param {string[]} errors
* @returns void
*/
function exitWithConfigurationErrors(errors) {
console.error("");
console.error("NOTE! Issues with configuration:");
for (const error of errors) {
console.error(`- ${error}`);
}
console.error("");
console.error("Please restart the bot after fixing the issues mentioned above.");
console.error("");
process.exit(1);
}
// https://github.com/ajv-validator/ajv/issues/141#issuecomment-270692820
const truthyValues = ["1", "true", "on", "yes"];
const falsyValues = ["0", "false", "off", "no"];
ajv.addKeyword({
keyword: "coerceBoolean",
compile() {
return (value, ctx) => {
if (! value) {
// Disabled -> no coercion
return true;
}
// https://github.com/ajv-validator/ajv/issues/141#issuecomment-270777250
// The "value" argument doesn't update within the same set of schemas inside "allOf",
// so we're referring to the original property instead.
// This also means we can't use { "type": "boolean" }, as it would test the un-updated data value.
const realValue = ctx.parentData[ctx.parentDataProperty];
if (typeof realValue === "boolean") {
return true;
}
if (truthyValues.includes(realValue)) {
ctx.parentData[ctx.parentDataProperty] = true;
} else if (falsyValues.includes(realValue)) {
ctx.parentData[ctx.parentDataProperty] = false;
} else {
return false;
}
return true;
};
},
});
ajv.addKeyword({
keyword: "multilineString",
compile() {
return (value, ctx) => {
if (! value) {
// Disabled -> no coercion
return true;
}
const realValue = ctx.parentData[ctx.parentDataProperty];
if (typeof realValue === "string") {
return true;
}
ctx.parentData[ctx.parentDataProperty] = realValue.join("\n");
return true;
};
},
});
const validate = ajv.compile(schema);
const configIsValid = validate(config);
if (! configIsValid) {
const errors = validate.errors.map(error => {
if (error.params.missingProperty) {
return `Missing required option: "${error.params.missingProperty}"`;
} else {
return `The "${error.instancePath.slice(1)}" option ${error.message}. (Is currently: ${typeof config[error.instancePath.slice(1)]})`;
}
});
exitWithConfigurationErrors(errors);
}
const validStreamingUrlRegex = /^https:\/\/(www\.)?twitch.tv\/[a-z\d_\-]+\/?$/i;
if (config.statusType === "streaming") {
if (! validStreamingUrlRegex.test(config.statusUrl)) {
exitWithConfigurationErrors([
"When statusType is set to \"streaming\", statusUrl must be set to a valid Twitch channel URL, such as https://www.twitch.tv/Dragory",
]);
}
}
console.log("Configuration ok!");
/**
* @type {ModmailConfig}
*/
module.exports = config;