-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathminigame-server.js
320 lines (260 loc) · 7.06 KB
/
minigame-server.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
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
var _ = require('lodash');
var fs = require('fs-extra');
var shortid = require('shortid');
var https = require('https');
var readline = require('readline');
var WebSocketServer = require('ws').Server;
var insults = require('./insults');
console.debug = _.noop;
var PORT = 6543;
var VERSION = 1; // protocol
var SAVE_VERSION = '1-alpha-1';
// Start with the default.
var pois = {};
var gameSettings = {
version: SAVE_VERSION,
gametype: 'crosslink',
pois: pois,
};
var measurementActive = false;
// parse arguments
if (process.argv.length < 3) {
console.error("need gamefile as first argument");
process.exit(1)
}
var gameFileName = process.argv[2];
/**
* Update the game config with new POI data.
* @param guid {String}
* @param data {Object}
*/
function handlePoiData(guid, data) {
console.info("New Poi Data:", data);
if (!pois[guid]) pois[guid] = {};
_.extend(pois[guid], data);
Client.broadcast({msg: 'poi', guid: guid, data: pois[guid]});
}
/**
* Add an event to the game history.
* @param event {Object}
*/
function handleEvent(event) {
console.info("Potentially New Event:", event);
}
var clients = {};
/**
* A game operating client.
*
* @constructor
* @param id {String} - a session id
* @param ws {WebSocket}
*/
function Client(id, ws) {
var self = this;
this.id = id;
this.connected = false;
this.ws = ws;
this.log("New Client!");
ws.on('message', function(message) {
self.debug("New Message:", message);
try {
var msg = JSON.parse(message);
} catch (e) {
return self.badLlama("failed to JSON decode message");
}
self.handle(msg)
});
clients[this.id] = this;
}
Client.prototype.log = function() {
console.log.apply(console, ["["+this.id+"]"].concat(_.values(arguments)));
};
Client.prototype.info = function() {
console.info.apply(console, ["["+this.id+"]"].concat(_.values(arguments)));
};
Client.prototype.debug = function() {
console.debug.apply(console, ["["+this.id+"]"].concat(_.values(arguments)));
};
/**
* Send a message to all connected clients.
* @param msg {Object}
*/
Client.broadcast = function(msg) {
_.each(clients, function(c) {c.send(msg)});
};
/**
* Close the connection and remove the client.
*/
Client.prototype.close = function() {
this.log("Going Away!");
try {
this.ws.close();
} catch(e) {
console.log("Failed to close ws:", e, ws);
}
delete clients[this.id];
};
/**
* Send a message to the client.
*
* @param msg {Object}
*/
Client.prototype.send = function(msg) {
if (this.connected) {
this.info("Sending:", msg);
try {
this.ws.send(JSON.stringify(msg));
} catch(e) {
console.log('Failed to send message over ws:', e, this.ws);
this.close();
}
} else {
//TODO buffer message
// In the meantime, drop the message on the floor.
}
};
/** Tell the client off for not following the protocol. */
Client.prototype.badLlama = function(reason) {
this.info("Bad Llama:", reason);
this.send({msg: 'badLlama', reason: reason, insult: insults.random()});
this.close();
};
/**
* Handle a message from the client.
* @param msg {Object}
*/
Client.prototype.handle = function(msg) {
this.info("Received:", msg);
if (this.connected) {
switch(msg.msg) {
case 'poi':
if ((typeof msg.guid) !== 'string' ||
(typeof msg.data) !== 'object' ||
(typeof msg.data.latE6) !== 'number' ||
(typeof msg.data.lngE6) !== 'number')
return this.badLlama("expecting `guid` to be string and `data` to be a correct object");
handlePoiData(msg.guid, msg.data);
break;
case 'event':
if ((typeof msg.type) !== 'string' ||
(typeof msg.timestamp) !== 'number' ||
(typeof msg.team) !== 'string')
return this.badLlama("`event` requires `type`, `timestamp`, and `team`");
handleEvent(msg);
break;
default:
return this.badLlama("unknown or unexpected message type `" + msg.msg + "`");
}
}
// Connecting
else {
if (msg.msg !== 'connect') return this.badLlama("expecting `connect`");
if (msg.version !== VERSION) {
this.send({msg: 'failed', version: VERSION});
return this.close();
}
if (msg.session !== undefined) {
//TODO recover session
this.send({msg: 'failed', version: VERSION});
return this.close();
}
this.connected = true;
this.send({msg: 'connected', session: this.id});
this.sendState();
}
};
/**
* Send the current game config and state to the client.
*/
Client.prototype.sendState = function() {
var self = this;
_.each(pois, function(poi, guid) {
self.send({msg:'poi', guid: guid, data: poi});
});
if (measurementActive) {
self.send({msg: 'start'});
}
};
// Set up the server.
var server = https.createServer({
key: fs.readFileSync('server.key.pem').toString(),
cert: fs.readFileSync('server.cert.pem').toString(),
}, function (req, res) {
res.writeHead(200);
res.end("You have successfully made your browser trust this server!\n\n");
});
var wss = new WebSocketServer({ server: server });
wss.on('connection', function(ws) {
console.debug("New Connection:", ws);
new Client(shortid.generate(), ws);
});
wss.on('error', function(e){
console.error(e);
});
// Load the game data.
if (fs.existsSync(gameFileName)) {
gameSettings = fs.readJsonSync(gameFileName);
pois = gameSettings.pois;
// Backup the game file in case we break it.
var i = 0;
function backupFileName(gf, i) { return gf + '.' + i + '.bak'; }
while (fs.existsSync(backupFileName(gameFileName, i))) ++i;
console.log("Backing up game file to", backupFileName(gameFileName, i));
fs.copySync(gameFileName, backupFileName(gameFileName, i));
}
else {
console.log("Using new game file", gameFileName);
}
// Set up the command line interface.
var rl = readline.createInterface(process.stdin, process.stdout);
rl.on('close', function() {
console.log("Bye");
console.info("Saving game settings to", gameFileName);
// Save the game settings to the file.
fs.writeJsonSync(gameFileName, gameSettings);
//TODO // Close the server.
process.exit();
});
function doPrompt() {
// Calculate the prompt
var prompt = [
(new Date()).toLocaleTimeString('en-GB'),
gameSettings.gametype,
_.keys(clients).length + " clients"
].join(", ") + "> ";
rl.setPrompt(prompt);
rl.prompt();
}
rl.on('line', function(line){
switch(line.trim()) {
case 'start':
if (measurementActive) {
console.log('Measurement is already active');
break;
}
Client.broadcast({msg: 'start'});
measurementActive = true;
break;
case 'end':
if (!measurementActive) {
console.log('Measurement is already not active');
break;
}
Client.broadcast({msg: 'end'});
measurementActive = false;
break;
case 'exit':
rl.close();
return;
break;
case 'help':
case '?':
console.log("try 'start', 'end', or 'exit'");
break;
}
doPrompt();
});
// Kick everything off.
server.listen(PORT);
console.log("Listening on port", PORT);
doPrompt();