forked from Team-Silver-Sphere/SquadJS
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathfactory.js
255 lines (196 loc) · 7.79 KB
/
factory.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
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
import Discord from 'discord.js';
import sequelize from 'sequelize';
import AwnAPI from './utils/awn-api.js';
import Logger from 'core/logger';
import SquadServer from './index.js';
import Plugins from './plugins/index.js';
const { Sequelize } = sequelize;
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export default class SquadServerFactory {
static async buildFromConfig(config) {
const plugins = await Plugins.getPlugins();
for (const plugin of Object.keys(plugins)) {
Logger.setColor(plugin, 'magentaBright');
}
// setup logging levels
for (const [module, verboseness] of Object.entries(config.logger.verboseness)) {
Logger.setVerboseness(module, verboseness);
}
for (const [module, color] of Object.entries(config.logger.colors)) {
Logger.setColor(module, color);
}
// create SquadServer
Logger.verbose('SquadServerFactory', 1, 'Creating SquadServer...');
const server = new SquadServer(config.server);
// initialise connectors
Logger.verbose('SquadServerFactory', 1, 'Preparing connectors...');
const connectors = {};
for (const pluginConfig of config.plugins) {
if (!pluginConfig.enabled) continue;
if (!plugins[pluginConfig.plugin])
throw new Error(`Plugin ${pluginConfig.plugin} does not exist.`);
const Plugin = plugins[pluginConfig.plugin];
for (const [optionName, option] of Object.entries(Plugin.optionsSpecification)) {
// ignore non connectors
if (!option.connector) continue;
// check the connector is listed in the options
if (!(optionName in pluginConfig))
throw new Error(
`${Plugin.name}: ${optionName} (${option.connector} connector) is missing.`
);
// get the name of the connector
const connectorName = pluginConfig[optionName];
// skip already created connectors
if (connectors[connectorName]) continue;
// create the connector
connectors[connectorName] = await SquadServerFactory.createConnector(
server,
option.connector,
connectorName,
config.connectors[connectorName]
);
}
}
// initialise plugins
Logger.verbose('SquadServerFactory', 1, 'Initialising plugins...');
for (const pluginConfig of config.plugins) {
if (!pluginConfig.enabled) continue;
if (!plugins[pluginConfig.plugin])
throw new Error(`Plugin ${pluginConfig.plugin} does not exist.`);
const Plugin = plugins[pluginConfig.plugin];
Logger.verbose('SquadServerFactory', 1, `Initialising ${Plugin.name}...`);
const plugin = new Plugin(server, pluginConfig, connectors);
// allow the plugin to do any asynchronous work needed before it can be mounted
await plugin.prepareToMount();
server.plugins.push(plugin);
}
return server;
}
static async createConnector(server, type, connectorName, connectorConfig) {
Logger.verbose('SquadServerFactory', 1, `Starting ${type} connector ${connectorName}...`);
if (type === 'discord') {
const connector = new Discord.Client();
await connector.login(connectorConfig);
return connector;
}
if (type === 'sequelize') {
let connector;
if (typeof connectorConfig === 'string') {
connector = new Sequelize(connectorConfig, {
define: {
charset: 'utf8mb4',
collate: 'utf8mb4_unicode_ci'
},
logging: (msg) => Logger.verbose('Sequelize', 3, msg)
});
} else if (typeof connectorConfig === 'object') {
connector = new Sequelize({
...connectorConfig,
logging: (msg) => Logger.verbose('Sequelize', 3, msg)
});
} else {
throw new Error('Unknown sequelize connector config type.');
}
await connector.authenticate();
return connector;
}
if (type === 'awnAPI') {
const awn = new AwnAPI(connectorConfig);
await awn.auth(connectorConfig);
return awn;
}
throw new Error(`${type.connector} is an unsupported connector type.`);
}
static parseConfig(configString) {
try {
return JSON.parse(configString);
} catch (err) {
throw new Error('Unable to parse config file.');
}
}
static buildFromConfigString(configString) {
Logger.verbose('SquadServerFactory', 1, 'Parsing config string...');
return SquadServerFactory.buildFromConfig(SquadServerFactory.parseConfig(configString));
}
static readConfigFile(configPath = './config.json') {
configPath = path.resolve(__dirname, '../', configPath);
if (!fs.existsSync(configPath)) throw new Error('Config file does not exist.');
return fs.readFileSync(configPath, 'utf8');
}
static buildFromConfigFile(configPath) {
Logger.verbose('SquadServerFactory', 1, 'Reading config file...');
return SquadServerFactory.buildFromConfigString(SquadServerFactory.readConfigFile(configPath));
}
static async buildConfig() {
const plugins = await Plugins.getPlugins();
const templatePath = path.resolve(__dirname, './templates/config-template.json');
const templateString = fs.readFileSync(templatePath, 'utf8');
const template = SquadServerFactory.parseConfig(templateString);
const pluginKeys = Object.keys(plugins).sort((a, b) =>
a.name < b.name ? -1 : a.name > b.name ? 1 : 0
);
for (const pluginKey of pluginKeys) {
const Plugin = plugins[pluginKey];
const pluginConfig = { plugin: Plugin.name, enabled: Plugin.defaultEnabled };
for (const [optionName, option] of Object.entries(Plugin.optionsSpecification)) {
pluginConfig[optionName] = option.default;
}
template.plugins.push(pluginConfig);
}
return template;
}
static async buildConfigFile() {
const configPath = path.resolve(__dirname, '../config.json');
const config = await SquadServerFactory.buildConfig();
const configString = JSON.stringify(config, null, 2);
fs.writeFileSync(configPath, configString);
}
static async buildReadmeFile() {
const plugins = await Plugins.getPlugins();
const pluginKeys = Object.keys(plugins).sort((a, b) =>
a.name < b.name ? -1 : a.name > b.name ? 1 : 0
);
const pluginInfo = [];
for (const pluginName of pluginKeys) {
const Plugin = plugins[pluginName];
const options = [];
for (const [optionName, option] of Object.entries(Plugin.optionsSpecification)) {
let optionInfo = `<li><h4>${optionName}${option.required ? ' (Required)' : ''}</h4>
<h6>Description</h6>
<p>${option.description}</p>
<h6>Default</h6>
<pre><code>${
typeof option.default === 'object'
? JSON.stringify(option.default, null, 2)
: option.default
}</code></pre></li>`;
if (option.example)
optionInfo += `<h6>Example</h6>
<pre><code>${
typeof option.example === 'object'
? JSON.stringify(option.example, null, 2)
: option.example
}</code></pre>`;
options.push(optionInfo);
}
pluginInfo.push(
`<details>
<summary>${Plugin.name}</summary>
<h2>${Plugin.name}</h2>
<p>${Plugin.description}</p>
<h3>Options</h3>
<ul>${options.join('\n')}</ul>
</details>`
);
}
const pluginInfoText = pluginInfo.join('\n\n');
const templatePath = path.resolve(__dirname, './templates/readme-template.md');
const template = fs.readFileSync(templatePath, 'utf8');
const readmePath = path.resolve(__dirname, '../README.md');
const readme = template.replace(/\/\/PLUGIN-INFO\/\//, pluginInfoText);
fs.writeFileSync(readmePath, readme);
}
}