-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
405 lines (366 loc) · 10.9 KB
/
server.js
File metadata and controls
405 lines (366 loc) · 10.9 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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
const express = require('express')
const session = require('express-session');
const bodyParser = require('body-parser');
const fs = require('fs');
const multer = require('multer')
const shell = require('shelljs');
const child_process = require('child_process');
const tk = require('tree-kill');
//Define Constants
const app = express()
const port = 3000;
const debuggingMode = false;
const viewOptions = { beautify: false };
const dbLocation = 'src/db.json';
const serverLocation = 'server-manager/servers/';
const pluginsLocation = 'server-manager/plugins/';
const jarsLocation = 'server-manager/jars/';
const openExplorer = require('open-file-explorer');
initializeBackend();
let jarList=updateJarList();
let pluginsList=updatePluginsList();
let ramInUse = 0;
global.serverInstances=[];
//Setup DB
var db = JSON.parse(fs.readFileSync(dbLocation));
function updateDB(){
let data=JSON.stringify(db,null,1);
fs.writeFileSync(dbLocation, data);
}
function updatePluginsList(){
let pluginsList = [];
filenames = fs.readdirSync(pluginsLocation);
filenames.forEach(file => {
pluginsList.push(file);
});
return pluginsList;
}
function removeRunningInstance(name){
for(i in global.serverInstances){
if(global.serverInstances[i].server.name==name){
global.serverInstances.splice(i, 1);
}
}
}
function updateJarList(){
let jarList = [];
filenames = fs.readdirSync(jarsLocation);
filenames.forEach(file => {
if(file!='BuildTools.jar' && file.includes('.jar')){
jarList.push(file);
}
});
return jarList;
}
function createWorld(name,ram,jar,plugins){
//Check for Duplicates
for(i in db.servers){
if(db.servers[i].name==name){
return false;
}
}
//Create Server
db['servers'].push(
{
"name":name,
"ram":ram,
"jar":jar,
"plugins":plugins
})
return true;
}
function deleteWorld(name,deleteFiles){ //TODO
for(i in db.servers){
if(db.servers[i].name==name){
db.servers.splice(i, 1);
break;
}
}
if(deleteFiles){
console.log("Would Remove World Files")
}
}
function stopWorld(name){
for(i in global.serverInstances){
if(global.serverInstances[i].server.name==name){
let pid = global.serverInstances[i].process.pid;
tk(pid); //Tree KIll
ramInUse-= parseInt(global.serverInstances[i].server.ram);
ramInUse = ramInUse>0? 0:ramInUse;
removeRunningInstance(name);
return true;
}
}
return false;
}
function updateServer(server){
for(s in db.servers){
if(db.servers[s].name==server.name){
db.servers[s]=server;
return;
}
}
return true;
}
function startWorld(name){
let server;
for(i in db.servers){
if(db.servers[i].name==name){
server=db.servers[i];
break;
}
}
if(!server){
return 'Server Not Found!';}
if(parseInt(server.ram)+ramInUse>db.ramCapacity){
return 'Launching a new Instance Uses Too Much Ram!'
}
let serverDir=serverLocation+`${name}/`
if(!fs.existsSync(serverDir)){
fs.mkdirSync(serverDir);
if(!fs.existsSync(`${serverDir}eula.txt`)){
fs.copyFileSync(`server-manager/default_eula.txt`, `${serverDir}eula.txt`,fs.constants.COPYFILE_EXCL);
}
if(!fs.existsSync(`${serverDir}ops.json`)){
fs.copyFileSync(`server-manager/default_ops.json`, `${serverDir}ops.json`,fs.constants.COPYFILE_EXCL);
}
fs.copyFileSync(`${jarsLocation}${server.jar}`, `${serverDir}${server.jar}`,fs.constants.COPYFILE_EXCL);
}
//Plugins Remove all and Recopy
fs.rmdirSync(`${serverDir}plugins/`, { recursive: true }, (err) => {
if (err) {
throw err;
}
});
fs.rmdirSync(`${serverDir}mods/`, { recursive: true }, (err) => {
if (err) {
throw err;
}
});
fs.mkdirSync(`${serverDir}plugins/`);
fs.mkdirSync(`${serverDir}mods/`);
for(i in server.plugins){
fs.copyFileSync(`${pluginsLocation}${server.plugins[i]}`, `${serverDir}plugins/${server.plugins[i]}`,fs.constants.COPYFILE_EXCL);
fs.copyFileSync(`${pluginsLocation}${server.plugins[i]}`, `${serverDir}mods/${server.plugins[i]}`,fs.constants.COPYFILE_EXCL);
}
//Jar Setup
if(!fs.existsSync(`${serverDir}${server.jar}`)){
fs.copyFileSync(`${jarsLocation}${server.jar}`, `${serverDir}${server.jar}`,fs.constants.COPYFILE_EXCL);
}
let command=`/usr/bin/java -Xmx${server.ram}M -Xms${server.ram}M -jar ${server.jar} nogui`;
let cp=child_process.exec(command,{cwd:`${serverDir}`,detached: true});
/* cp.stdout.on('data', (data) => {
console.log(`child stdout:\n${data}`);
});*/
/*cp.stderr.on('data', (data) => {
console.log(`child stderr:\n${data}`);
});*/
cp.addListener('close', (evt) =>{
console.log('Closed!');
removeRunningInstance(name);
});
global.serverInstances.push({ server:server,process:cp});
ramInUse+=parseInt(server.ram);
return 'started';
}
function initializeBackend(){
if(!fs.existsSync('server-manager/')){
fs.mkdirSync('server-manager/');}
if(!fs.existsSync(serverLocation)){
fs.mkdirSync(serverLocation);}
if(!fs.existsSync(jarsLocation)){
fs.mkdirSync(jarsLocation);}
if(!fs.existsSync(pluginsLocation)){
fs.mkdirSync(pluginsLocation);}
updateJarList();
updatePluginsList();
}
//Set Up Express session and View engine
app.use(session({secret: 'ssshhhhh',saveUninitialized: false,resave: false}));
app.use(express.static('src/public/', {dotfiles:'deny'} ))
app.set('views', __dirname + '/views');
app.set('view engine', 'jsx');
app.engine('jsx', require('express-react-views').createEngine(viewOptions));
app.use(bodyParser.json({limit: '50mb'})) // parse application/json
app.use(bodyParser.urlencoded({ limit:'50mb', extended: false})) // parse application/x-www-form-urlencoded
//Router Plain Requests
app.get('/', checkCredentials, function (req, res) {
res.redirect('/control-panel');
});
app.get('/control-panel', checkCredentials, function (req, res) {
res.render('ControlPanel.jsx',{servers:db.servers,
ramCapacity:db.ramCapacity,
riu:ramInUse,
jarList,
pluginsList
});
});
app.get('/create-server', checkCredentials, function (req, res) {
res.render('ControlPanel.jsx',{servers:db.servers,
ramCapacity:db.ramCapacity,
riu:ramInUse,
jarList,
pluginsList,
content:'create'
});
});
//Server Control
app.get('/open-server-directory',checkCredentials,function(req,res){
let name = req.query.name
if(fs.existsSync(serverLocation+name)){
openExplorer(serverLocation+name, err => {
if(err) {
console.log(err);
}
else {
console.log('Gucci?');
}
});
}
res.redirect('/');
});
app.post('/update-changes',checkCredentials,function(req,res){
let err;
for(server in req.body){
let err = updateServer(req.body[server]);
if(err){
console.log('ERROR UPDATING')
break;
}
}
if(!err){
updateDB();
}
res.redirect('/');
});
app.post('/create-new-server',checkCredentials,function(req,res){
let err;
for(s in db.servers){
if(db.servers[s].name==req.body.name){
err=True;
}
}
if(!err){
filenames = fs.readdirSync(serverLocation);
filenames.forEach(file => {
if(req.body.name==file){
let counter=0;
let backupLocation=`${serverLocation}${file}-old(${counter})`;
do{
counter++
backupLocation=`${serverLocation}${file}-old(${counter})`;
}while(fs.existsSync(backupLocation));
fs.renameSync(`${serverLocation}${file}`, backupLocation, err => {
if(err)
return console.error(err);
});
}
});
db.servers.push(req.body);
updateDB();
}
res.redirect('/');
});
app.get('/stop-all',checkCredentials,function(req,res){
let length = global.serverInstances.length;
for(let i = 0;i < length;i++){
let success = stopWorld(global.serverInstances[0].server.name)
if(!success){
console.log('ERROR STOPPING SERVER: '+global.serverInstances[s].name);
}
}
res.redirect('/');
});
app.get('/stop-world',checkCredentials, function (req, res) {
let name = req.query.name
for(s in global.serverInstances){
let success
if(global.serverInstances[s].server.name==name){
success = stopWorld(name)
}
if(!success){
console.log('ERROR STOPPING SERVER: '+name);
}
}
res.redirect('/');
});
app.get('/delete-world',checkCredentials, function (req, res) {
let name = req.query.name
deleteWorld(name,false); //false means keep files
updateDB();
res.redirect('/');
});
app.get('/start-world',checkCredentials, function (req, res) {
let name = req.query.name
let status = startWorld(name);
if(status!='started'){
console.log(status)
}
res.redirect('/');
});
//Upload Events
app.post('/uploadWorld',checkCredentials,function(req,res){
});
app.post('/credentialsChange',checkCredentials,function(req,res){
});
app.get('/worldDownload',checkCredentials, function (req, res){
let path = req.originalUrl.substring(23,req.originalUrl.length)
let file = __dirname+"/uploads/public/"+path;
res.download(file);
});
//Authentication
app.get('/logout',function(req,res){
delete req.session.user_id;
res.redirect('/');
if (req.session.returnTo) {
delete req.session.returnTo
}
});
app.post('/logout',function(req,res){
res.redirect('/logout');
});
app.post('/login',function(req,res){
let username = req.body.username?req.body.username:undefined;
let password = req.body.password;
let isValid = db.username==username && db.password==password;
if(isValid)
req.session.user_id=0;
res.redirect('/');
});
app.get('/login', function (req, res) {
res.render('Login.jsx');
});
function checkCredentials(req, res, next) {
req.session.user_id=0;
if (req.session.user_id!=undefined || req.path==='/login') {
next();
} else {
res.redirect( `/login`);
}
}
//Server Handlers
app.get('/page-not-found',function(req,res){
res.redirect( `/`);
});
//Debugging mode Handler
if(!debuggingMode){
app.get('*', function(req, res) {
res.redirect('/page-not-found');
});
app.post('*', function(req, res) {
res.redirect('/page-not-found');
});
}
//Serve App
function startServer() {
server = app.listen(port, function () {
console.log('Node version:' + process.versions.node);
console.log(`Web Server listening on port ${port}!`);
});
server.timeout = 10 * 60 * 1000;
server.on('connection', function(socket) {
// 10 minutes timeout
socket.setTimeout(10 * 60 * 1000);
});
}
startServer();