-
Notifications
You must be signed in to change notification settings - Fork 4
/
brickadia.js
208 lines (173 loc) · 6.5 KB
/
brickadia.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
/* Represents a brickadia server */
const fs = require('fs');
const readline = require('readline');
const { spawn, execSync } = require('child_process');
const stripAnsi = require('strip-ansi');
const PROGRAM_PATH =
'brickadia/Brickadia/Binaries/Linux/BrickadiaServer-Linux-Shipping';
const CONFIG_PATH = 'brickadia/Brickadia/Saved/Config/LinuxServer';
const SAVES_PATH = 'brickadia/Brickadia/Saved/Builds';
const GAME_SERVER_SETTINGS = CONFIG_PATH + '/ServerSettings.ini';
const BRICKADIA_FILENAME = 'Brickadia_Alpha4_Patch1_CL3642_Linux.tar.xz';
const BRICKADIA_URL = 'https://static.brickadia.com/builds/CL3642/' +
BRICKADIA_FILENAME;
const DEFAULT_SERVER_NAME = 'Brikkit Server';
const DEFAULT_SERVER_DESC = 'Get Brikkit at https://github.com/n42k/brikkit';
const DEFAULT_SERVER_MAX_PLAYERS = 20;
class Brickadia {
constructor(configuration) {
if(this._getBrickadiaIfNeeded())
this._writeDefaultConfiguration();
if(process.env.EMAIL === undefined ||
process.env.PASSWORD === undefined ||
process.env.PORT === undefined) {
throw new Error('Email or password are not set!');
}
// get user email and password, and server port based on env vars
const userArg = `-User="${process.env.EMAIL}"`;
const passwordArg = `-Password="${process.env.PASSWORD}"`;
const portArg = `-port="${process.env.PORT}"`;
// start brickadia with aforementioned arguments
// note that the unbuffer program is required,
// otherwise the io will eventually stop
this._spawn = spawn('unbuffer',
['-p', PROGRAM_PATH, 'BrickadiaServer',
'-NotInstalled', '-log', userArg, passwordArg, portArg]);
this._spawn.stdin.setEncoding('utf8');
this._callbacks = {
close: [],
exit: [],
out: [],
err: []
};
this._watchers = [];
this._spawn.on('close', code => {
for(const callback of this._callbacks['close'])
callback(code);
});
this._spawn.on('exit', code => {
for(const callback of this._callbacks['exit'])
callback(code);
});
const errRl = readline.createInterface({
input: this._spawn.stderr,
terminal: false
});
errRl.on('line', line => {
for(const callback of this._callbacks['err'])
callback(line);
});
const outRl = readline.createInterface({
input: this._spawn.stdout,
terminal: false
});
outRl.on('line', line => {
line = stripAnsi(line);
for (let i = 0; i < this._watchers.length; i++) {
const watcher = this._watchers[i];
try {
// if the matcher is regex, match on regex, if it is a function, use that
const match = watcher.matcher instanceof RegExp
? line.match(watcher.matcher)
: watcher.matcher(line);
if (match) {
watcher.resolve(match);
this._watchers.splice(i, 1);
}
} catch (e) {
console.error('Error in console matcher', e);
}
}
for(const callback of this._callbacks['out'])
callback(line);
});
const sp = this._spawn;
process.on('SIGINT', () => {
sp.kill();
process.exit();
});
process.on('uncaughtException', _err => {
sp.kill();
});
}
// wait for stdout to match this regex, returns the match or times out
waitForLine(matcher, timeoutDelay=100) {
return new Promise((resolve, reject) => {
let timeout;
// create the watcher
const watcher = {
matcher,
resolve: (...args) => {
clearTimeout(timeout);
resolve(...args);
},
}
// if the delay is non 0, kill the promise after some time
if (timeoutDelay !== 0) {
timeout = setTimeout(() => {
// remove the watcher if it exists
const index = this._watchers.indexOf(watcher);
if (index > -1)
this._watchers.splice(index, 0);
// reject the promise
reject('timed out');
}, timeoutDelay);
}
this._watchers.push(watcher);
});
}
/*
* Types available:
* 'close': on normal brickadia close
* args: code
* 'exit': on abnormal brickadia termination
* args: code
* 'out': on anything being written to stdout
* args: line
* 'err': on anything being written to stderr
* args: line
*/
on(type, callback) {
if(this._callbacks[type] === undefined)
throw new Error('Undefined Brickadia.on type.');
this._callbacks[type].push(callback);
}
write(line) {
this._spawn.stdin.write(line);
}
_writeDefaultConfiguration(configuration) {
execSync(`mkdir -p ${CONFIG_PATH}`);
fs.writeFileSync(GAME_SERVER_SETTINGS,
`[Server__BP_ServerSettings_General_C BP_ServerSettings_General_C]
MaxSelectedBricks=1000
MaxPlacedBricks=1000
SelectionTimeout=2.000000
PlaceTimeout=2.000000
ServerName=${DEFAULT_SERVER_NAME}
ServerDescription=${DEFAULT_SERVER_DESC}
ServerPassword=
MaxPlayers=${DEFAULT_SERVER_MAX_PLAYERS}
bPubliclyListed=True
WelcomeMessage="<color=\\"0055ff\\">Welcome to <b>{2}</>, {1}.</>"
bGlobalRulesetSelfDamage=True
bGlobalRulesetPhysicsDamage=False`);
}
// returns whether downloading brickadia was needed
_getBrickadiaIfNeeded() {
if(fs.existsSync('brickadia') &&
fs.existsSync(PROGRAM_PATH) &&
!fs.existsSync(BRICKADIA_FILENAME))
return false;
execSync(`rm -f ${BRICKADIA_FILENAME}`);
execSync(`wget ${BRICKADIA_URL}`, {
stdio: [null, process.stdout, process.stderr]});
execSync(`rm -rf brickadia/*`);
execSync(`mkdir -p brickadia`);
execSync(`pv ${BRICKADIA_FILENAME} | tar xJp -C brickadia`, {
stdio: [null, process.stdout, process.stderr]});
execSync(`rm ${BRICKADIA_FILENAME}`);
execSync(`mkdir -p ${SAVES_PATH}`);
return true;
}
}
module.exports = Brickadia;