This repository was archived by the owner on Jan 8, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
executable file
·346 lines (276 loc) · 8.94 KB
/
Copy pathserver.js
File metadata and controls
executable file
·346 lines (276 loc) · 8.94 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
#!/usr/bin/env node
// codplayer web control widget server
//
// Copyright 2013-2014 Peter Liljenberg <peter.liljenberg@gmail.com>
//
// Distributed under an MIT license, please see LICENSE in the top dir.
'use strict';
var jf = require('jsonfile');
var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server, { 'log level': 1 });
var zmq = require('zmq');
var numClients = 0;
var isSubscribed = false;
var currentState = null;
var currentRipState = null;
var currentDisc = null;
//
// Read config
//
var configPath;
var config;
if (process.argv.length === 2) {
configPath = __dirname + '/config.json';
}
else if (process.argv.length === 3) {
configPath = process.argv[2];
}
else {
console.error('Usage: %s %s [config.json]', process.argv[0], process.argv[1]);
process.exit(1);
}
console.log('reading config from: %s', configPath);
try {
config = jf.readFileSync(configPath);
}
catch (err) {
console.error('error reading ' + configPath + ': ' + err);
process.exit(1);
}
var checkConfigParam = function(param, type) {
if (!config[param]) {
console.error('missing config parameter: %s', param);
process.exit(1);
}
if (typeof config[param] !== type) {
console.error('expected %s config parameter for %s, got: %j', type, param, config[param]);
process.exit(1);
}
};
checkConfigParam('serverPort', 'number');
checkConfigParam('commandEndpoint', 'string');
checkConfigParam('stateEndpoint', 'string');
//
// Web server setup
//
app.use(express.static(__dirname + '/static'));
app.get('/', function(req, res) {
res.sendfile(__dirname + '/static/codctl.html');
});
server.listen(config.serverPort, function() {
console.log('Server listening on port ' + config.serverPort);
});
//
// ZeroMQ stuff
//
// Forward function declarations
var sendCommand;
var queueCommand;
var stateSocket;
var commandSocket;
var currentCommand = null;
var commandTimeout = null;
var commandQueue = [];
// Handily, both state updates and command responses can be handled
// with the same function
var onSocketMessage = function(type, value) {
type = type.toString();
value = value.toString();
switch (type) {
case 'state':
try {
currentState = JSON.parse(value);
}
catch (e) {
console.log('invalid state: %j', value);
io.sockets.emit('cod-error', 'Malformed state update from codplayer');
return;
}
io.sockets.emit('cod-state', currentState);
// Make sure that our information on the disc is in sync with
// the state. We might start getting updates in the middle of
// playing or just miss the disc updates.
if (currentState.disc_id) {
if (!currentDisc || currentState.disc_id !== currentDisc.disc_id) {
console.log('missing current disc, fetching it: %s', currentState.disc_id);
currentDisc = null;
// Queue a source command, unless it is already in progress
if (currentCommand !== 'source') {
queueCommand(['source']);
}
}
}
else {
if (currentDisc) {
console.log('no disc, dropping current disc: %s', currentDisc.disc_id);
currentDisc = null;
io.sockets.emit('cod-disc', null);
}
}
break;
case 'rip_state':
try {
currentRipState = JSON.parse(value);
}
catch (e) {
console.log('invalid rip state: %j', value);
io.sockets.emit('cod-error', 'Malformed rip state update from codplayer');
return;
}
// Just forward to client, as we mostly care more about being
// told what the player is doing with the CD reader rather
// than exactly which disc is being read
io.sockets.emit('cod-rip-state', currentRipState);
break;
case 'disc':
try {
currentDisc = JSON.parse(value);
}
catch (e) {
console.log('invalid disc: %j', value);
return;
}
io.sockets.emit('cod-disc', currentDisc);
break;
case 'error':
console.log('codplayer sent an error: %s', value);
io.sockets.emit('cod-error', value);
break;
case 'ok':
break;
default:
console.log('unexpected message: %j', type);
}
};
var openStateSocket = function() {
stateSocket = zmq.socket('sub');
stateSocket.on('error', function(err) {
console.log('state socket error: %j', err);
io.sockets.emit('cod-error', err);
});
stateSocket.on('message', onSocketMessage);
stateSocket.connect(config.stateEndpoint);
// We don't subscribe until there's a client
};
var openCommandSocket = function() {
commandSocket = zmq.socket('req');
commandSocket.on('error', function(err) {
console.log('command socket error: %j', err);
io.sockets.emit('cod-error', err);
});
commandSocket.on('message', function(type, value) {
console.log('%s response: %s %s', currentCommand, type, value);
currentCommand = null;
clearTimeout(commandTimeout);
commandTimeout = null;
// Fire off the next queued command, if any, before the
// processing of this response may trigger anything itself
if (commandQueue.length > 0) {
sendCommand(commandQueue.shift());
}
onSocketMessage(type, value);
});
// Don't let unsent messages linger when we reopen
commandSocket.linger = 0;
commandSocket.connect(config.commandEndpoint);
};
/* Send a command now, dropping anything in progress */
sendCommand = function(cmdargs) {
var cmd = cmdargs[0];
if (currentCommand) {
console.log('unfinished command %s replaced by %s', currentCommand, cmd);
commandSocket.close();
openCommandSocket();
}
currentCommand = cmd;
console.log('sending command: %j', cmdargs);
commandSocket.send(cmdargs);
// It doesn't make sense waiting a long time for commands to take
// effect, since this mirrors the UI of a CD player.
commandTimeout = setTimeout(
function() {
console.log('timeout sending command: %s', currentCommand);
io.sockets.emit('cod-error', 'No response from server');
currentCommand = null;
commandTimeout = null;
// reopen socket to drop the queued command
commandSocket.close();
openCommandSocket();
if (commandQueue.length > 0) {
sendCommand(commandQueue.shift());
}
},
5000);
};
/* Queue a command to be run when any command in progress finished */
queueCommand = function(cmdargs) {
if (currentCommand) {
commandQueue.push(cmdargs);
}
else {
sendCommand(cmdargs);
}
};
openStateSocket();
openCommandSocket();
//
// Socket callbacks
//
io.sockets.on('connection', function (socket) {
numClients++;
console.log('connection, now ' + numClients + ' clients');
if (!isSubscribed) {
// Start subscribing to all state updates
isSubscribed = true;
stateSocket.subscribe('');
// And force a state fetch in case there's nothing coming from the server
queueCommand(['state']);
queueCommand(['rip_state']);
queueCommand(['source']);
}
else {
// Tell new client immediately about current state, which
// should be ok since there are other clients
if (currentState) {
socket.emit('cod-state', currentState);
}
if (currentRipState) {
socket.emit('cod-rip-state', currentRipState);
}
if (currentDisc) {
socket.emit('cod-disc', currentDisc);
}
else {
socket.emit('cod-disc', null);
}
}
socket.on('disconnect', function () {
numClients--;
console.log('disconnect, now ' + numClients + ' clients');
if (numClients === 0) {
// Stop listening if there aren't any clients
// after 30 secs
setTimeout(function() {
if (numClients !== 0) {
return;
}
// Still no clients, no need to keep listening
console.log('unsubscribing to state updates');
isSubscribed = false;
stateSocket.unsubscribe('');
// Which also means that the state is no longer updated,
// so don't cache it
currentState = null;
currentRipState = null;
currentDisc = null;
}, 30000);
}
});
socket.on('cod-command', function (data) {
var command = data.command.split(' ');
console.log('got command: %j', command);
sendCommand(command);
});
});