forked from RanvierMUD/ranviermud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ranvier
executable file
·351 lines (300 loc) · 9.06 KB
/
ranvier
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
#!/usr/bin/env node
/**
* Main file, use this to run the server:
* node ranvier [options]
*
* Options:
* -v Verbose loggin
* --port Port to listen on
* --locale Locale to act as the default
* --save Minutes between autosave
* --respawn Minutes between respawn
*/
// built-ins
var net = require('net'),
util = require('util'),
express = require('express'),
// local
Commands = require('./src/commands').Commands,
Rooms = require('./src/rooms').Rooms,
Npcs = require('./src/npcs').Npcs,
Items = require('./src/items').Items,
Data = require('./src/data').Data,
Events = require('./src/events').Events,
Plugins = require('./src/plugins'),
PlayerManager = require('./src/player_manager').PlayerManager,
// third party
Localize = require('localize'),
argv = require('optimist').argv,
telnet = require('./src/3rdparty/telnet.js');
/**
* These aren't really globals, they're only "global" to this file,
* we'll pass them around via construction as needed
*/
// cmdline options
var locale = argv.locale || 'en',
port = argv.port || 6250,
verbose = !!argv.v,
save_interval = isNaN(parseInt(argv.save, 10)) ? 10 : parseInt(argv.save, 10), // number of minutes between autosave ticks
respawn_interval = isNaN(parseInt(argv.respawn, 10)) ? 20 : parseInt(argv.respawn, 10), // "" between respawn tickets
//storage of main game entities
players,
rooms = new Rooms(),
items = new Items(),
npcs = new Npcs(),
server,
// Stuff for the server executable
l10n,
respawnint,
saveint;
/**
* Do the dirty work
*/
var init = function (restart_server)
{
util.log("START - Loading entities");
players = new PlayerManager([]);
restart_server = typeof restart_server === 'undefined' ? true : restart_server;
Commands.configure({
rooms: rooms,
players: players,
items: items,
npcs: npcs,
locale: locale
});
Events.configure({
players: players,
items: items,
locale: locale,
npcs: npcs,
rooms: rooms
});
if (restart_server) {
util.log("START - Starting server");
/**
* Effectively the 'main' game loop but not really because it's a REPL
*/
server = new telnet.Server(function (socket) {
socket.on('interrupt', function () {
socket.write("\n*interrupt*\n");
});
// Register all of the events
for (var event in Events.events) {
socket.on(event, Events.events[event]);
}
socket.write("Connecting...\n");
util.log("User connected...");
// @see: src/events.js - Events.events.login
socket.emit('login', socket);
});
// start the server
server.listen(port);
// save every 10 minutes
util.log("Setting autosave to " + save_interval + " minutes.");
clearInterval(saveint);
var saveint = setInterval(save, save_interval * 60000);
// respawn every 20 minutes, probably a better way to do this
util.log("Setting respawn to " + respawn_interval + " minutes.");
clearInterval(respawnint);
var respawnint = setInterval(load, respawn_interval * 60000);
clearInterval(loggingint);
var loggingint = setInterval(logging, 60000);
Plugins.init(true, {
players: players,
items: items,
locale: locale,
npcs: npcs,
rooms: rooms,
server: server
});
}
load(function (success) {
if (success) {
util.log("Server started...");
server.emit('startup');
} else {
process.exit(1);
}
});
};
// START IT UP!
init();
/**
* Logging the statistics
*/
// Helper function to create a valid key for JavaScript
function dateToStr(dt) { return 'D' + String(dt.getFullYear()) + '_' + String((dt.getMonth() + 1)) + '_' + String(dt.getDate()); }
function logging() {
var fs = require('fs'),
daily = {},
current = [],
dailyFile = '',
currentFile = '';
try {
dailyFile = fs.readFileSync('./stats/daily.counts', 'ascii');
if (dailyFile !== false) daily = JSON.parse(dailyFile);
} catch (err) { }
try {
currentFile = fs.readFileSync('./stats/current.counts', 'ascii');
if (currentFile !== false) current = JSON.parse(currentFile);
} catch (err) { }
if (current.length > 60) { current.shift(); }
var now = new Date();
var dateStr = dateToStr(now);
current.push({dt: now.getTime(), count: players.players.length});
if (Object.keys(daily).length == 0) {
daily = JSON.parse('{"' + dateStr + '":{"current":0,"high":0,"hours":[]}}');
} else if (typeof(daily[dateStr]) == 'undefined') {
var days30 = now;
daily[dateStr] = { current: 0, high: 0, hours: [] };
days30.setDate(days30.getDate() - 30);
if (Object.keys(daily).length > 30) { delete daily[dateToStr(days30)]; }
util.log(JSON.stringify(daily));
}
daily[dateStr].current = players.players.length;
daily[dateStr].high = ( daily[dateStr].high < daily[dateStr].current ? daily[dateStr].current : daily[dateStr].high );
if (typeof(daily[dateStr].hours) == 'undefined') { daily[dateStr].hours = []; }
if (typeof(daily[dateStr].hours[now.getHours()]) == 'undefined') { daily[dateStr].hours[now.getHours()] = 0; }
daily[dateStr].hours[now.getHours()] = ( daily[dateStr].hours[now.getHours()] < daily[dateStr].current ? daily[dateStr].current : daily[dateStr].hours[now.getHours()] );
fs.writeFileSync('./stats/daily.counts', JSON.stringify(daily), 'ascii');
fs.writeFileSync('./stats/current.counts', JSON.stringify(current), 'ascii');
}
/**
* Save all connected players
*/
function save()
{
util.log("Saving...");
players.each(function (p) {
p.save();
});
util.log("Done");
}
/**
* Load rooms, items, npcs. Register items and npcs to their base locations.
* Configure the event and command modules after load. Doubles as a "respawn"
*/
function load(callback)
{
util.log("Loading rooms...");
rooms.load(verbose, function () {
util.log("Done.");
util.log("Loading items...");
items.load(verbose, function () {
util.log("Done.");
util.log("Adding items to rooms...");
items.each(function (item) {
if (item.getRoom()) {
var room = rooms.getAt(item.getRoom());
if (!room.hasItem(item.getUuid())) {
room.addItem(item.getUuid());
}
}
});
util.log("Done.");
util.log("Loading npcs...")
npcs.load(verbose, function () {
util.log("Done.");
util.log("Adding npcs to rooms...");
npcs.each(function (npc) {
if (npc.getRoom()) {
var room =rooms.getAt(npc.getRoom());
if (!room.hasNpc(npc.getUuid())) {
room.addNpc(npc.getUuid());
}
}
});
util.log("Done.");
if (callback) {
callback(true);
}
});
})
});
}
// Not game stuff, this is for the server executable
process.stdin.setEncoding('utf8');
l10n = new Localize(require('js-yaml').load(require('fs').readFileSync(__dirname + '/l10n/server.yml').toString('utf8')), undefined, 'zz');
/**
* Commands that the server executable itself accepts
*/
var server_commands = {
/**
* Hotboot, AKA do everything involved with a restart but keep players connected
*/
hotboot : function (args)
{
args = args ? args.split(' ') : [];
var warn = args[0] && args[0] === 'warn';
var time = args[0] ? parseInt(args[warn ? 1 : 0], 10) : 0;
if (time && time < 20) {
console.log("Gotta give the players a bit longer than that, might as well do it instantly...");
return;
}
time = time ? time * 1000 : 0;
if (warn) {
warn = function (interval) {
players.broadcastL10n(l10n, 'HOTBOOT_WARN', interval);
players.each(function(p) {p.prompt();});
};
warn(time / 1000 + " seconds");
setTimeout(function () { warn(Math.floor((time / 4) / 1000) + " seconds"); }, time - Math.floor(time / 4));
}
util.log("HOTBOOTING SERVER" + (time ? " IN " + (time / 1000) + " SECONDS " : ''));
setTimeout(function () {
util.log("HOTBOOTING...");
save();
init(false);
}, time);
},
/**
* Hard restart: saves and disconnects all connected players
*/
restart: function (args)
{
args = args ? args.split(' ') : [];
var warn = args[0] && args[0] === 'warn';
var time = args[0] ? parseInt(args[warn ? 1 : 0], 10) : 0;
if (time && time < 20) {
console.log("Gotta give the players a bit longer than that, might as well do it instantly...");
return;
}
time = time ? time * 1000 : 0;
if (warn) {
warn = function (interval) {
players.broadcastL10n(l10n, 'RESTART_WARN', interval);
players.each(function(p) {p.prompt();});
};
warn(time / 1000 + " seconds");
setTimeout(function () { warn(Math.floor((time / 4) / 1000) + " seconds"); }, time - Math.floor(time / 4));
}
util.log("RESTARTING SERVER" + (time ? " IN " + (time / 1000) + " SECONDS " : ''));
setTimeout(function () {
util.log("RESTARTING...");
save();
server.emit('shutdown');
server.close();
players.each(function (p) { p.getSocket().end(); });
init(true);
}, time);
}
};
//
//process.on('SIGINT', function ()
//{
// util.log("Shutting down - not so gracefully...");
// process.exit(0);
//});
//
process.stdin.resume();
process.stdin.on('data', function (data)
{
data = data.trim();
var command = data.split(' ')[0];
if (!(command in server_commands)) {
console.log("That's not a real command...");
return;
}
server_commands[command](data.split(' ').slice(1).join(' '));
});
// vim: set syn=javascript :