-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathindex.js
604 lines (477 loc) · 16 KB
/
index.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
var http = require('http');
var util = require('util');
var EventEmitter = require('events').EventEmitter;
var et = require('elementtree');
var parseUrl = require('url').parse;
var os = require('os');
var concat = require('concat-stream');
var address = require('network-address');
var debug = require('debug')('upnp-device-client');
var pkg = require('./package.json');
var OS_VERSION = [os.platform(), os.release()].join('/');
var PACKAGE_VERSION = [pkg.name, pkg.version].join('/');
var SUBSCRIPTION_TIMEOUT = 300;
function DeviceClient(url) {
EventEmitter.call(this);
this.url = url;
this.deviceDescription = null;
this.serviceDescriptions = {};
this.server = null;
this.listening = false;
this.subscriptions = {};
}
util.inherits(DeviceClient, EventEmitter);
DeviceClient.prototype.getDeviceDescription = function(callback) {
var self = this;
// Use cache if available
if(this.deviceDescription) {
process.nextTick(function() {
callback(null, self.deviceDescription);
});
return;
}
debug('fetch device description');
fetch(this.url, function(err, body) {
if(err) return callback(err);
var desc = parseDeviceDescription(body, self.url);
self.deviceDescription = desc // Store in cache for next call
callback(null, desc);
});
};
DeviceClient.prototype.getServiceDescription = function(serviceId, callback) {
var self = this;
serviceId = resolveService(serviceId);
this.getDeviceDescription(function(err, desc) {
if(err) return callback(err);
var service = desc.services[serviceId];
if(!service) {
var err = new Error('Service ' + serviceId + ' not provided by device');
err.code = 'ENOSERVICE';
return callback(err);
}
// Use cache if available
if(self.serviceDescriptions[serviceId]) {
return callback(null, self.serviceDescriptions[serviceId]);
}
debug('fetch service description (%s)', serviceId);
fetch(service.SCPDURL, function(err, body) {
if(err) return callback(err);
var desc = parseServiceDescription(body);
self.serviceDescriptions[serviceId] = desc; // Store in cache for next call
callback(null, desc);
});
});
};
DeviceClient.prototype.callAction = function(serviceId, actionName, params, callback) {
var self = this;
serviceId = resolveService(serviceId);
this.getServiceDescription(serviceId, function(err, desc) {
if(err) return callback(err);
if(!desc.actions[actionName]) {
var err = new Error('Action ' + actionName + ' not implemented by service');
err.code = 'ENOACTION';
return callback(err);
}
var service = self.deviceDescription.services[serviceId];
// Build SOAP action body
var envelope = et.Element('s:Envelope');
envelope.set('xmlns:s', 'http://schemas.xmlsoap.org/soap/envelope/');
envelope.set('s:encodingStyle', 'http://schemas.xmlsoap.org/soap/encoding/');
var body = et.SubElement(envelope, 's:Body');
var action = et.SubElement(body, 'u:' + actionName);
action.set('xmlns:u', service.serviceType);
Object.keys(params).forEach(function(paramName) {
var tmp = et.SubElement(action, paramName);
var value = params[paramName];
tmp.text = (value === null)
? ''
: params[paramName].toString();
});
var doc = new et.ElementTree(envelope);
var xml = doc.write({
xml_declaration: true,
});
// Send action request
var options = parseUrl(service.controlURL);
options.method = 'POST';
options.headers = {
'Content-Type': 'text/xml; charset="utf-8"',
'Content-Length': xml.length,
'Connection': 'close',
'SOAPACTION': '"' + service.serviceType + '#' + actionName + '"'
};
debug('call action %s on service %s with params %j', actionName, serviceId, params);
var req = http.request(options, function(res) {
res.pipe(concat(function(buf) {
var doc = et.parse(buf.toString());
if(res.statusCode !== 200) {
var errorCode = doc.findtext('.//errorCode');
var errorDescription = doc.findtext('.//errorDescription').trim();
var err = new Error(errorDescription + ' (' + errorCode + ')');
err.code = 'EUPNP';
err.statusCode = res.statusCode;
err.errorCode = errorCode;
return callback(err);
}
// Extract response outputs
var serviceDesc = self.serviceDescriptions[serviceId];
var actionDesc = serviceDesc.actions[actionName];
var outputs = actionDesc.outputs.map(function(desc) {
return desc.name;
});
var result = {};
outputs.forEach(function(name) {
result[name] = doc.findtext('.//' + name);
});
callback(null, result)
}));
});
req.on('error', callback);
req.end(xml);
});
};
DeviceClient.prototype.subscribe = function(serviceId, listener) {
var self = this;
serviceId = resolveService(serviceId);
if(this.subscriptions[serviceId]) {
// If we already have a subscription to this service,
// add the provided callback to the listeners and return
this.subscriptions[serviceId].listeners.push(listener);
return;
}
// If there's no subscription to this service, create one
// by first fetching the event subscription URL ...
this.getDeviceDescription(function(err, desc) {
if(err) return self.emit('error', err);
var service = desc.services[serviceId];
if(!service) {
var err = new Error('Service ' + serviceId + ' not provided by device');
err.code = 'ENOSERVICE';
return self.emit('error', err);
}
// ... and ensuring the event server is created and listening
self.ensureEventingServer(function() {
var options = parseUrl(service.eventSubURL);
var server = self.server;
options.method = 'SUBSCRIBE';
options.headers = {
'HOST': options.host,
'USER-AGENT': [OS_VERSION, 'UPnP/1.1', PACKAGE_VERSION].join(' '),
'CALLBACK': '<http://' + server.address().address + ':' + server.address().port + '/>',
'NT': 'upnp:event',
'TIMEOUT': 'Second-' + SUBSCRIPTION_TIMEOUT
};
var req = http.request(options, function(res) {
if(res.statusCode !== 200) {
var err = new Error('SUBSCRIBE error');
err.statusCode = res.statusCode;
self.releaseEventingServer();
self.emit('error', err);
return;
}
var sid = res.headers['sid'];
var timeout = parseTimeout(res.headers['timeout']);
function renew() {
debug('renew subscription to %s', serviceId);
var options = parseUrl(service.eventSubURL);
options.method = 'SUBSCRIBE';
options.headers = {
'HOST': options.host,
'SID': sid,
'TIMEOUT': 'Second-' + SUBSCRIPTION_TIMEOUT
};
var req = http.request(options, function(res) {
if(res.statusCode !== 200) {
var err = new Error('SUBSCRIBE renewal error');
err.statusCode = res.statusCode;
// XXX: should we clear the subscription and release the server here ?
self.emit('error', err);
return;
}
var timeout = parseTimeout(res.headers['timeout']);
var renewTimeout = Math.max(timeout - 30, 30); // renew 30 seconds before expiration
debug('renewing subscription to %s in %d seconds', serviceId, renewTimeout);
var timer = setTimeout(renew, renewTimeout * 1000);
self.subscriptions[serviceId].timer = timer;
});
req.on('error', function(err) {
self.emit('error', err);
});
req.end();
}
var renewTimeout = Math.max(timeout - 30, 30); // renew 30 seconds before expiration
debug('renewing subscription to %s in %d seconds', serviceId, renewTimeout);
var timer = setTimeout(renew, renewTimeout * 1000);
self.subscriptions[serviceId] = {
sid: sid,
url: service.eventSubURL,
timer: timer,
listeners: [listener]
};
});
req.on('error', function(err) {
self.releaseEventingServer();
self.emit('error', err);
});
req.end();
});
});
};
DeviceClient.prototype.unsubscribe = function(serviceId, listener) {
var self = this;
serviceId = resolveService(serviceId);
// First make sure there are subscriptions for this service ...
var subscription = this.subscriptions[serviceId];
if(!subscription) return;
// ... and we know about this listener
var idx = subscription.listeners.indexOf(listener);
if(idx === -1) return;
// Remove the listener from the list
subscription.listeners.splice(idx, 1);
if(subscription.listeners.length === 0) {
// If there's no listener left for this service, unsubscribe from it
debug('unsubscribe from service %s', serviceId);
var options = parseUrl(subscription.url);
options.method = 'UNSUBSCRIBE';
options.headers = {
'HOST': options.host,
'SID': subscription.sid
};
var req = http.request(options, function(res) {
if(res.statusCode !== 200) {
var err = new Error('UNSUBSCRIBE error');
err.statusCode = res.statusCode;
return self.emit('error', err);
}
clearTimeout(self.subscriptions[serviceId].timer);
delete self.subscriptions[serviceId];
// Make sure the eventing server is shutdown if there is no
// subscription left for any service
self.releaseEventingServer();
});
req.on('error', function(err) {
self.emit('error', err);
});
req.end();
}
};
DeviceClient.prototype.ensureEventingServer = function(callback) {
var self = this;
if(!this.server) {
debug('create eventing server');
this.server = http.createServer(function(req, res) {
req.pipe(concat(function(buf) {
var sid = req.headers['sid'];
var seq = req.headers['seq'];
var events = parseEvents(buf);
debug('received events %s %d %j', sid, seq, events);
var keys = Object.keys(self.subscriptions);
var sids = keys.map(function(key) {
return self.subscriptions[key].sid;
})
var idx = sids.indexOf(sid);
if(idx === -1) {
debug('WARNING unknown SID %s', sid);
// silently ignore unknown SIDs
return;
}
var serviceId = keys[idx];
var listeners = self.subscriptions[serviceId].listeners;
// Dispatch each event to each listener registered for
// this service's events
listeners.forEach(function(listener) {
events.forEach(function(e) {
listener(e);
});
});
}));
});
this.server.listen(0, address.ipv4());
}
if(!this.listening) {
this.server.on('listening', function() {
self.listening = true;
callback();
});
} else {
process.nextTick(callback);
}
};
DeviceClient.prototype.releaseEventingServer = function() {
if(Object.keys(this.subscriptions).length === 0) {
debug('shutdown eventing server');
this.server.close();
this.server = null;
this.listening = false;
}
};
function parseEvents(buf) {
var events = [];
var doc = et.parse(buf.toString());
var lastChange = doc.findtext('.//LastChange');
if(lastChange) {
// AVTransport and RenderingControl services embed event data
// in an `<Event></Event>` element stored as an URIencoded string.
doc = et.parse(lastChange);
// The `<Event></Event>` element contains one `<InstanceID></InstanceID>`
// subtree per stream instance reporting its status.
var instances = doc.findall('./InstanceID');
instances.forEach(function(instance) {
var data = {
InstanceID: Number(instance.get('val'))
};
instance.findall('./*').forEach(function(node) {
data[node.tag] = node.get('val');
});
events.push(data);
});
} else {
// In any other case, each variable is stored separately in a
// `<property></property>` tag
var data = {};
doc.findall('./property/*').forEach(function(node) {
data[node.tag] = node.text;
});
events.push(data);
}
return events;
}
function parseTimeout(header) {
return Number(header.split('-')[1]);
}
function parseDeviceDescription(xml, url) {
var doc = et.parse(xml);
var desc = extractFields(doc.find('./device'), [
'deviceType',
'friendlyName',
'manufacturer',
'manufacturerURL',
'modelName',
'modelNumber',
'modelDescription',
'UDN'
]);
var nodes = doc.findall('./device/iconList/icon');
desc.icons = nodes.map(function(icon) {
return extractFields(icon, [
'mimetype',
'width',
'height',
'depth',
'url'
]);
});
var nodes = doc.findall('./device/serviceList/service');
desc.services = {};
nodes.forEach(function(service) {
var tmp = extractFields(service, [
'serviceType',
'serviceId',
'SCPDURL',
'controlURL',
'eventSubURL'
]);
var id = tmp.serviceId;
delete tmp.serviceId;
desc.services[id] = tmp;
});
// Make URLs absolute
var baseUrl = extractBaseUrl(url);
desc.icons.map(function(icon) {
icon.url = buildAbsoluteUrl(baseUrl, icon.url);
return icon;
});
Object.keys(desc.services).forEach(function(id) {
var service = desc.services[id];
service.SCPDURL = buildAbsoluteUrl(baseUrl, service.SCPDURL);
service.controlURL = buildAbsoluteUrl(baseUrl, service.controlURL);
service.eventSubURL = buildAbsoluteUrl(baseUrl, service.eventSubURL);
});
return desc;
}
function parseServiceDescription(xml) {
var doc = et.parse(xml);
var desc = {};
desc.actions = {};
var nodes = doc.findall('./actionList/action');
nodes.forEach(function(action) {
var name = action.findtext('./name');
var inputs = [];
var outputs = [];
var nodes = action.findall('./argumentList/argument');
nodes.forEach(function(argument) {
var arg = extractFields(argument, [
'name',
'direction',
'relatedStateVariable'
]);
var direction = arg.direction;
delete arg.direction;
if(direction === 'in') inputs.push(arg);
else outputs.push(arg);
});
desc.actions[name] = {
inputs: inputs,
outputs: outputs
};
});
desc.stateVariables = {};
var nodes = doc.findall('./serviceStateTable/stateVariable');
nodes.forEach(function(stateVariable) {
var name = stateVariable.findtext('./name');
var nodes = stateVariable.findall('./allowedValueList/allowedValue');
var allowedValues = nodes.map(function(allowedValue) {
return allowedValue.text;
});
desc.stateVariables[name] = {
dataType: stateVariable.findtext('./dataType'),
sendEvents: stateVariable.get('sendEvents'),
allowedValues: allowedValues,
defaultValue: stateVariable.findtext('./defaultValue')
};
});
return desc;
}
function fetch(url, callback) {
var req = http.get(url, function(res) {
if(res.statusCode !== 200) {
var err = new Error('Request failed');
err.statusCode = res.statusCode;
return callback(err);
}
res.pipe(concat(function(buf) {
callback(null, buf.toString())
}));
});
req.on('error', callback);
req.end();
}
function extractFields(node, fields) {
var data = {};
fields.forEach(function(field) {
var value = node.findtext('./' + field);
if(typeof value !== 'undefined') {
data[field] = value;
}
});
return data;
}
function buildAbsoluteUrl(base, url) {
if(url === '') return '';
if(url.substring(0, 4) === 'http') return url;
if(url[0] === '/') {
var root = base.split('/').slice(0, 3).join('/'); // http://host:port
return root + url;
} else {
return base + '/' + url;
}
}
function extractBaseUrl(url) {
return url.split('/').slice(0, -1).join('/');
}
function resolveService(serviceId) {
return (serviceId.indexOf(':') === -1)
? 'urn:upnp-org:serviceId:' + serviceId
: serviceId;
}
module.exports = DeviceClient;