forked from nep-tv/node-emberplus-sdpgen
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
executable file
·657 lines (584 loc) · 21.5 KB
/
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
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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
const EventEmitter = require('events').EventEmitter;
const util = require('util');
const S101Server = require('./client.js').S101Server;
const ember = require('./ember.js');
function TreeServer(host, port, tree) {
TreeServer.super_.call(this);
var self = this;
self._debug = false;
self.callback = undefined;
self.timeoutValue = 2000;
self.server = new S101Server(host, port);
self.tree = tree;
self.clients = new Set();
self.subscribers = {};
self.server.on('listening', () => {
if (self._debug) { console.log("listening"); }
self.emit('listening');
if (self.callback !== undefined) {
self.callback();
self.callback = undefined;
}
});
self.server.on('connection', (client) => {
if (self._debug) { console.log("ember new connection from", client.remoteAddress()); }
self.clients.add(client);
client.on("emberTree", (root) => {
if (self._debug) { console.log("ember new request from", client.remoteAddress(), root); }
// Queue the action to make sure responses are sent in order.
client.addRequest(() => {
try {
let path = self.handleRoot(client, root);
self.emit("request", {client: client.remoteAddress(), root: root, path: path});
}
catch(e) {
if (self._debug) { console.log(e.stack); }
self.emit("error", e);
}
});
});
client.on("disconnected", () => {
self.clients.delete(client);
self.emit('disconnect', client.remoteAddress());
});
client.on("error", error => {
self.emit('clientError', { remoteAddress: client.remoteAddress(), error });
});
self.emit('connection', client.remoteAddress());
});
self.server.on('disconnected', () => {
self.emit('disconnected', client.remoteAddress());
});
self.server.on("error", (e) => {
self.emit("error", e);
if (self.callback !== undefined) {
self.callback(e);
}
});
}
util.inherits(TreeServer, EventEmitter);
TreeServer.prototype.listen = function() {
return new Promise((resolve, reject) => {
this.callback = (e) => {
if (e === undefined) {
return resolve();
}
return reject(e);
};
this.server.listen();
});
};
TreeServer.prototype.close = function () {
return new Promise((resolve, reject) => {
this.callback = (e) => {
if (e === undefined) {
return resolve();
}
return reject(e);
};
this.server.server.close();
});
};
TreeServer.prototype.handleRoot = function(client, root) {
if ((root === undefined) || (root.elements === undefined) || (root.elements < 1)) {
this.emit("error", new Error("invalid request"));
return;
}
const node = root.elements[0];
client.request = node;
if (node.path !== undefined) {
return this.handleQualifiedNode(client, node);
}
else if (node instanceof ember.Command) {
// Command on root element
this.handleCommand(client, this.tree, node.number);
return "root";
}
else {
return this.handleNode(client, node);
}
}
TreeServer.prototype.handleError = function(client, node) {
if (client !== undefined) {
let res = node == null ? this.tree._root.getMinimal() : node;
client.sendBERNode(res);
}
}
TreeServer.prototype.handleQualifiedNode = function(client, node) {
const path = node.path;
// Find this element in our tree
const element = this.tree.getElementByPath(path);
if ((element === null) || (element === undefined)) {
this.emit("error", new Error(`unknown element at path ${path}`));
return this.handleError(client);
}
if ((node.children !== undefined) && (node.children.length === 1) &&
(node.children[0] instanceof ember.Command)) {
this.handleCommand(client, element, node.children[0].number);
}
else {
if (node instanceof ember.QualifiedMatrix) {
this.handleQualifiedMatrix(client, element, node);
}
else if (node instanceof ember.QualifiedParameter) {
this.handleQualifiedParameter(client, element, node);
}
}
return path;
}
TreeServer.prototype.handleNode = function(client, node) {
// traverse the tree
let element = node;
let path = [];
while(element !== undefined) {
if (element.number === undefined) {
this.emit("error", "invalid request");
return;
}
if (element instanceof ember.Command) {
break;
}
path.push(element.number);
let children = element.getChildren();
if ((! children) || (children.length === 0)) {
break;
}
element = element.children[0];
}
let cmd = element;
if (cmd === undefined) {
this.emit("error", "invalid request");
return this.handleError(client);
}
element = this.tree.getElementByPath(path.join("."));
if (element == null) {
this.emit("error", new Error(`unknown element at path ${path}`));
return this.handleError(client);
}
if (cmd instanceof ember.Command) {
this.handleCommand(client, element, cmd.number);
}
else if ((cmd instanceof ember.MatrixNode) && (cmd.connections !== undefined)) {
this.handleMatrixConnections(client, element, cmd.connections);
}
else if ((cmd instanceof ember.Parameter) &&
(cmd.contents !== undefined) && (cmd.contents.value !== undefined)) {
if (this._debug) { console.log(`setValue for element at path ${path} with value ${cmd.contents.value}`); }
this.setValue(element, cmd.contents.value, client);
let res = this.getResponse(element._parent);
client.sendBERNode(res);
this.updateSubscribers(element.getPath(), res, client);
}
else {
this.emit("error", new Error("invalid request format"));
if (this._debug) { console.log("invalid request format"); }
return this.handleError(client, element.getTreeBranch());
}
return path;
}
TreeServer.prototype.handleQualifiedMatrix = function(client, element, matrix)
{
this.handleMatrixConnections(client, element, matrix.connections);
}
TreeServer.prototype.handleQualifiedParameter = function(client, element, parameter)
{
if (parameter.contents.value !== undefined) {
this.setValue(element, parameter.contents.value, client);
let res = this.getQualifiedResponse(element._parent);
client.sendBERNode(res);
this.updateSubscribers(element.getPath(), res, client);
}
}
TreeServer.prototype.handleMatrixConnections = function(client, matrix, connections, response = true) {
var res;
var root; // ember message root
if (matrix.isQualified()) {
root = new ember.Root();
res = new ember.QualifiedMatrix(matrix.path);
root.elements = [res]; // do not use addchild or the element will get removed from the tree.
}
else {
res = new ember.MatrixNode(matrix.number);
root = matrix._parent.getTreeBranch(res);
}
res.connections = {};
for(let id in connections) {
if (!connections.hasOwnProperty(id)) {
continue;
}
let connection = connections[id];
let conResult = new ember.MatrixConnection(connection.target);
let emitType;
res.connections[connection.target] = conResult;
// Apply changes
if ((connection.operation === undefined) ||
(connection.operation.value == ember.MatrixOperation.absolute)) {
matrix.connections[connection.target].setSources(connection.sources);
emitType = "matrix-change";
}
else if (connection.operation == ember.MatrixOperation.connect) {
matrix.connections[connection.target].connectSources(connection.sources);
emitType = "matrix-connect";
}
else { // Disconnect
matrix.connections[connection.target].disconnectSources(connection.sources);
emitType = "matrix-disconnect";
}
// Send response or update subscribers.
if (response) {
conResult.sources = matrix.connections[connection.target].sources;
conResult.disposition = ember.MatrixDisposition.modified;
// We got a request so emit something.
this.emit(emitType, {
target: connection.target,
sources: connection.sources,
client: client.remoteAddress()
});
}
else {
// the action has been applied. So we should either send the current state (absolute)
// or send the action itself (connection.sources)
conResult.sources = matrix.connections[connection.target].sources;
conResult.operation = ember.MatrixOperation.absolute;
}
}
if (client !== undefined) {
client.sendBERNode(root);
}
else {
this.updateSubscribers(matrix.getPath(), root, client);
}
}
const validateMatrixOperation = function(matrix, target, sources) {
if (matrix === undefined) {
throw new Error(`matrix not found with path ${path}`);
}
if (matrix.contents === undefined) {
throw new Error(`invalid matrix at ${path} : no contents`);
}
if (matrix.contents.targetCount === undefined) {
throw new Error(`invalid matrix at ${path} : no targetCount`);
}
if ((target < 0) || (target >= matrix.contents.targetCount)) {
throw new Error(`target id ${target} out of range 0 - ${matrix.contents.targetCount}`);
}
if (sources.length === undefined) {
throw new Error("invalid sources format");
}
}
const doMatrixOperation = function(server, path, target, sources, operation) {
let matrix = server.tree.getElementByPath(path);
validateMatrixOperation(matrix, target, sources);
let connection = new ember.MatrixConnection(target);
connection.sources = sources;
connection.operation = operation;
server.handleMatrixConnections(undefined, matrix, [connection], false);
}
TreeServer.prototype.matrixConnect = function(path, target, sources) {
doMatrixOperation(this, path, target, sources, ember.MatrixOperation.connect);
}
TreeServer.prototype.matrixDisconnect = function(path, target, sources) {
doMatrixOperation(this, path, target, sources, ember.MatrixOperation.disconnect);
}
TreeServer.prototype.matrixSet = function(path, target, sources) {
doMatrixOperation(this, path, target, sources, ember.MatrixOperation.absolute);
}
TreeServer.prototype.handleCommand = function(client, element, cmd) {
if (cmd === ember.GetDirectory) {
this.handleGetDirectory(client, element);
}
else if (cmd === ember.Subscribe) {
this.handleSubscribe(client, element);
}
else if (cmd === ember.Unsubscribe) {
this.handleUnSubscribe(client, element);
}
else {
this.emit("error", new Error(`invalid command ${cmd}`));
}
}
TreeServer.prototype.getResponse = function(element) {
return element.getTreeBranch(undefined, function(node) {
node.update(element);
let children = element.getChildren();
if (children != null) {
for (let i = 0; i < children.length; i++) {
node.addChild(children[i].getDuplicate());
}
}
else if (this._debug) {
console.log("getResponse","no children");
}
});
}
TreeServer.prototype.getQualifiedResponse = function(element) {
let res = new ember.Root();
let dup = element.toQualified();
let children = element.getChildren();
if (children != null) {
for (let i = 0; i < children.length; i++) {
dup.addChild(children[i].getDuplicate());
}
}
res.elements = [dup];
return res;
}
TreeServer.prototype.handleGetDirectory = function(client, element) {
if (client !== undefined) {
if ((element.isMatrix() || element.isParameter()) &&
(!element.isStream())) {
// ember spec: parameter without streamIdentifier should
// report their value changes automatically.
this.subscribe(client, element);
}
let res;
if (client.request.path == null) {
res = this.getResponse(element);
}
else {
res = this.getQualifiedResponse(element);
}
client.sendBERNode(res);
}
}
TreeServer.prototype.handleSubscribe = function(client, element) {
this.subscribe(client, element);
}
TreeServer.prototype.handleUnSubscribe = function(client, element) {
this.unsubscribe(client, element);
}
TreeServer.prototype.subscribe = function(client, element) {
const path = element.getPath();
if (this.subscribers[path] === undefined) {
this.subscribers[path] = new Set();
}
this.subscribers[path].add(client);
}
TreeServer.prototype.unsubscribe = function(client, element) {
const path = element.getPath();
if (this.subscribers[path] === undefined) {
return;
}
this.subscribers[path].delete(client);
}
TreeServer.prototype.setValue = function(element, value, origin, key) {
return new Promise((resolve, reject) => {
// Change the element value if write access permitted.
if (element.contents !== undefined) {
if (element.isParameter()) {
if ((element.contents.access !== undefined) &&
(element.contents.access.value > 1)) {
element.contents.value = value;
this.emit("value-change", element);
}
}
else if (element.isMatrix()) {
if ((key !== undefined) && (element.contents.hasOwnProperty(key))) {
element.contents[key] = value;
this.emit("value-change", element);
}
}
}
});
}
TreeServer.prototype.replaceElement = function(element) {
let path = element.getPath();
let parent = this.tree.getElementByPath(path);
if ((parent === undefined)||(parent._parent === undefined)) {
throw new Error(`Could not find element at path ${path}`);
}
parent = parent._parent;
let children = parent.getChildren();
let newList = [];
for(let i = 0; i <= children.length; i++) {
if (children[i] && children[i].getPath() == path) {
element._parent = parent; // move it to new tree.
children[i] = element;
let res = this.getResponse(element);
this.updateSubscribers(path,res);
return;
}
}
}
TreeServer.prototype.updateSubscribers = function(path, response, origin) {
if (this.subscribers[path] === undefined) {
return;
}
for (let client of this.subscribers[path]) {
if (client === origin) {
continue; // already sent the response to origin
}
if (this.clients.has(client)) {
client.queueMessage(response);
}
else {
// clean up subscribers - client is gone
this.subscribers[path].delete(client);
}
}
}
const parseObj = function(parent, obj) {
let path = parent.getPath();
for(let i = 0; i < obj.length; i++) {
let emberElement;
let content = obj[i];
let number = content.number !== undefined ? content.number : (i+1);
delete content.number;
if (content.value !== undefined) {
emberElement = new ember.Parameter(number);
emberElement.contents = new ember.ParameterContents(content.value);
if (content.type) {
emberElement.contents.type = ember.ParameterType.get(content.type);
delete content.type;
}
else {
emberElement.contents.type = ember.ParameterType.string;
}
if (content.access) {
emberElement.contents.access = ember.ParameterAccess.get(content.access);
delete content.access;
}
else {
emberElement.contents.access = ember.ParameterAccess.read;
}
}
else if (content.targetCount !== undefined) {
emberElement = new ember.MatrixNode(number);
emberElement.contents = new ember.MatrixContents();
if (content.labels) {
emberElement.contents.labels = [];
for(let l = 0; l < content.labels.length; l++) {
emberElement.contents.labels.push(
new ember.Label(content.labels[l])
);
}
delete content.labels;
}
if (content.connections) {
emberElement.connections = {};
for (let c in content.connections) {
if (! content.connections.hasOwnProperty(c)) {
continue;
}
let t = content.connections[c].target !== undefined ? content.connections[c].target : 0;
let connection = new ember.MatrixConnection(t);
connection.setSources(content.connections[c].sources);
emberElement.connections[t] = connection;
}
delete content.connections;
}
else {
emberElement.connections = {};
for (let t = 0; t < content.targetCount; t++) {
let connection = new ember.MatrixConnection(t);
emberElement.connections[t] = connection;
}
}
}
else {
emberElement = new ember.Node(number);
emberElement.contents = new ember.NodeContents();
}
for(let id in content) {
if ((id !== "children") && (content.hasOwnProperty(id))) {
if ((typeof content[id] === 'object') && content.contents.value == undefined) {
for (let key in content[id]) {
emberElement.contents[key] = content[id][key];
}
} else if (content.contents.value !== undefined) {
emberElement = new ember.Parameter(number);
emberElement.contents = new ember.ParameterContents(content.contents.value);
if (content.contents.identifier) {
emberElement.contents.identifier = content.contents.identifier;
}
else {
emberElement.contents.identifier = "param" + number;
}
if (content.contents.type) {
emberElement.contents.type = ember.ParameterType.get(content.contents.type);
delete content.contents.type;
}
else {
emberElement.contents.type = ember.ParameterType.string;
}
if (content.contents.access) {
emberElement.contents.access = ember.ParameterAccess.get(content.contents.access);
delete content.contents.access;
}
else {
emberElement.contents.access = ember.ParameterAccess.read;
}
} else {
emberElement.contents[id] = content[id];
}
}else {
parseObj(emberElement, content.children);
}
}
parent.addChild(emberElement);
}
}
TreeServer.JSONtoTree = function(obj) {
let tree = new ember.Root();
parseObj(tree, obj);
return tree;
}
const toJSON = function(node) {
let res = {};
if (node.number) {
res.number = node.number
}
if (node.path) {
res.path = node.path;
}
if (node.contents) {
for(let prop in node.contents) {
if (node.contents.hasOwnProperty(prop)) {
let type = typeof node.contents[prop];
if ((type === "string") || (type === "number")) {
res[prop] = node.contents[prop];
}
else if (node.contents[prop].value !== undefined) {
res[prop] = node.contents[prop].value;
}
else {
res[prop] = node.contents[prop];
}
}
}
}
if (node.isMatrix()) {
if (node.targets) {
res.targets = node.targets.slice(0);
}
if (node.sources) {
res.sources = node.sources.slice(0);
}
if (node.connections) {
res.connections = {};
for (let target in connections) {
if (connections.hasOwnProperty(target)) {
res.connections[target] = {target: target, sources: []};
if (connections[target].sources) {
res.connections[target].sources = connections[target].sources.slice(0);
}
}
}
}
}
let children = node.getChildren();
if (children) {
res.children = [];
for(let child of children) {
res.children.push(toJSON(child));
}
}
return res;
};
TreeServer.prototype.toJSON = function() {
if ((!this.tree) || (!this.tree.elements) || (this.tree.elements.length == 0)) {
return [];
}
return [].push(toJSON(this.tree.elements[0]));
};
module.exports = TreeServer;