-
Notifications
You must be signed in to change notification settings - Fork 240
/
cam.js
953 lines (896 loc) · 31 KB
/
cam.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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
/**
* @namespace cam
* @description Common camera module
* @author Andrew D.Laptev <a.d.laptev@gmail.com>
* @licence MIT
*/
const http = require('http')
, crypto = require('crypto')
, util = require('util')
, events = require('events')
, url = require('url')
, linerase = require('./utils').linerase
, parseSOAPString = require('./utils').parseSOAPString
, emptyFn = function() {}
;
/**
* @callback Cam~MessageCallback
* @property {?Error} error
* @property {?string} message
*/
/**
* @callback Cam~ConnectionCallback
* @property {?Error} error
*/
/**
* Camera class
* @param {object} options
* @param {string} options.hostname
* @param {string} [options.username]
* @param {string} [options.password]
* @param {number} [options.port=80]
* @param {string} [options.path=/onvif/device_service]
* @param {number} [options.timeout=120000]
* @param {boolean} [options.preserveAddress=false] Force using hostname and port from constructor for the services
* @param {Cam~ConnectionCallback} [callback]
* @fires Cam#rawRequest
* @fires Cam#rawResponse
* @fires Cam#connect
* @fires Cam#event
* @fires Cam#warning
* @property presets
* @class
* @constructor
* @extends events.EventEmitter
* @example
* var
* http = require('http'),
* Cam = require('onvif').Cam;
*
* new Cam({
* hostname: <CAMERA_HOST>,
* username: <USERNAME>,
* password: <PASSWORD>
* }, function(err) {
* this.absoluteMove({x: 1, y: 1, zoom: 1});
* this.getStreamUri({protocol:'RTSP'}, function(err, stream) {
* http.createServer(function (req, res) {
* res.writeHead(200, {'Content-Type': 'text/html'});
* res.end('<html><body>' +
* '<embed type="application/x-vlc-plugin" target="' + stream.uri + '"></embed>' +
* '</body></html>');
* }).listen(3030);
* });
* });
*/
var Cam = function(options, callback) {
callback = callback || emptyFn;
this.hostname = options.hostname;
this.username = options.username;
this.password = options.password;
this.port = options.port || 80;
this.path = options.path || '/onvif/device_service';
this.timeout = options.timeout || 120000;
this.agent = options.agent || false;
/**
* Force using hostname and port from constructor for the services
* @type {boolean}
*/
this.preserveAddress = options.preserveAddress || false;
this.events = {};
setImmediate(function() {
this.connect(callback);
}.bind(this));
};
// events.EventEmitter inheritance
util.inherits(Cam, events.EventEmitter);
/**
* Connect to the camera and fill device information properties
* @param {Cam~ConnectionCallback} callback
*/
Cam.prototype.connect = function(callback) {
// Must execute getSystemDataAndTime (and wait for callback)
// before any other ONVIF commands so that the time of the ONVIF device
// is known
this.getSystemDateAndTime(function(err, date, xml) {
if (err) {
return callback.call(this, err, null, xml);
}
this.getCapabilities(function(err, data, xml) {
if (err) {
return callback.call(this, err, null, xml);
} else {
var upstartFunctions = [];
// Profile S
if (data && data.media && data.media.XAddr) {
upstartFunctions.push(this.getProfiles);
upstartFunctions.push(this.getVideoSources);
}
var count = upstartFunctions.length;
var errCall = false;
if (count > 0) {
upstartFunctions.forEach(function(fun) {
fun.call(this, function(err) {
if (err) {
if (callback && !errCall) {
callback.call(this, err);
errCall = true;
return;
}
} else {
if (!--count) {
this.getActiveSources();
/**
* Indicates that device is connected.
* @event Cam#connect
*/
this.emit('connect');
if (callback) {
return callback.call(this, err);
}
}
}
}.bind(this));
}.bind(this));
} else {
this.emit('connect');
if (callback) {
return callback.call(this, false);
}
}
}
}.bind(this));
}.bind(this));
};
/**
* @callback Cam~RequestCallback
* @param {Error} err
* @param {object} [response] message
* @param {string} [xml] response
*/
/**
* Common camera request
* @param {object} options
* @param {string} [options.service] Name of service (ptz, media, etc)
* @param {string} options.body SOAP body
* @param {string} [options.url] Defines another url to request
* @param {boolean} [options.ptz] make request to PTZ uri or not
* @param {Cam~RequestCallback} callback response callback
* @private
*/
Cam.prototype._request = function(options, callback) {
if (typeof callback !== 'function') {
throw new Error('`callback` must be a function');
}
var _this = this;
var callbackExecuted = false;
var reqOptions = options.url || {
hostname: this.hostname
, port: this.port
, agent: this.agent //Supports things like https://www.npmjs.com/package/proxy-agent which provide SOCKS5 and other connections
, path: options.service
? (this.uri[options.service] ? this.uri[options.service].path : options.service)
: this.path
, timeout: this.timeout
};
reqOptions.headers = {
'Content-Type': 'application/soap+xml'
, 'Content-Length': Buffer.byteLength(options.body, 'utf8')//options.body.length chinese will be wrong here
, charset: 'utf-8'
};
reqOptions.method = 'POST';
var req = http.request(reqOptions, function(res) {
var bufs = [], length = 0;
res.on('data', function(chunk) {
bufs.push(chunk);
length += chunk.length;
});
res.on('end', function() {
if (callbackExecuted === true) {
return;
}
callbackExecuted = true;
var xml = Buffer.concat(bufs, length).toString('utf8');
/**
* Indicates raw xml response from device.
* @event Cam#rawResponse
* @type {string}
*/
_this.emit('rawResponse', xml);
parseSOAPString(xml, callback);
});
});
req.setTimeout(this.timeout, function() {
if (callbackExecuted === true) {
return;
} else {
callbackExecuted = true;
}
callback(new Error('Network timeout'));
req.abort();
});
req.on('error', function(err) {
if (callbackExecuted === true) {
return;
}
callbackExecuted = true;
/* address, port number or IPCam error */
if (err.code === 'ECONNREFUSED' && err.errno === 'ECONNREFUSED' && err.syscall === 'connect') {
callback(err);
/* network error */
} else if (err.code === 'ECONNRESET' && err.errno === 'ECONNRESET' && err.syscall === 'read') {
callback(err);
} else {
callback(err);
}
});
/**
* Indicates raw xml request to device.
* @event Cam#rawRequest
* @type {Object}
*/
this.emit('rawRequest', options.body);
req.write(options.body);
req.end();
};
/**
* @callback Cam~DateTimeCallback
* @property {?Error} error
* @property {Date} dateTime Date object of current device's dateTime
* @property {string} xml Raw SOAP response
*/
/**
* Receive date and time from cam
* @param {Cam~DateTimeCallback} callback
*/
Cam.prototype.getSystemDateAndTime = function(callback) {
// The ONVIF spec says this should work without a Password as we need to know any difference in the
// remote NVT's time relative to our own time clock (called the timeShift) so we can calculate the
// correct timestamp in nonce authentication header.
// But.. Panasonic and Digital Barriers both have devices that implement ONVIF that only work with
// authenticated getSystemDateAndTime
this._request({
body:
'<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope">' +
'<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">' +
'<GetSystemDateAndTime xmlns="http://www.onvif.org/ver10/device/wsdl"/>' +
'</s:Body>' +
'</s:Envelope>'
}, function(err, data, xml) {
if (!err) {
try {
var dt = linerase(data[0]['getSystemDateAndTimeResponse'][0]['systemDateAndTime'][0]['UTCDateTime'][0])
, time = new Date(Date.UTC(dt.date.year, dt.date.month - 1, dt.date.day, dt.time.hour, dt.time.minute, dt.time.second))
;
if (!this.timeShift) {
this.timeShift = time - Date.now();
}
callback.call(this, err, time, xml);
} catch (err) {
callback.call(this, err, null, xml);
}
}
if (err) {
if (xml && xml.toLowerCase().includes('sender not authorized')) {
// Try again with a Username and Password
this._request({
body: this._envelopeHeader() +
'<GetSystemDateAndTime xmlns="http://www.onvif.org/ver10/device/wsdl"/>' +
this._envelopeFooter()
}, function(err, data, xml) {
try {
var dt = linerase(data[0]['getSystemDateAndTimeResponse'][0]['systemDateAndTime'][0]['UTCDateTime'][0])
, time = new Date(Date.UTC(dt.date.year, dt.date.month - 1, dt.date.day, dt.time.hour, dt.time.minute, dt.time.second))
;
if (!this.timeShift) {
this.timeShift = time - Date.now();
}
callback.call(this, err, time, xml);
} catch (err) {
callback.call(this, err, null, xml);
}
}.bind(this));
} else {
callback.call(this, err, null, xml);
}
}
}.bind(this));
};
/**
* @typedef {object} Cam~SystemDateAndTime
* @property {string} dayTimeType (Manual | NTP)
* @property {boolean} daylightSavings
* @property {string} timezone in POSIX 1003.1 format
* @property {number} hour
* @property {number} minute
* @property {number} second
* @property {number} year
* @property {number} month
* @property {number} day
*/
/**
* Set the device system date and time
* @param {object} options
* @param {Date} [options.dateTime]
* @param {string} options.dateTimeType (Manual | NTP)
* @param {boolean} [options.daylightSavings=false]
* @patam {string} [options.timezone]
* @param {Cam~DateTimeCallback} callback
*/
Cam.prototype.setSystemDateAndTime = function(options, callback) {
if (['Manual', 'NTP'].indexOf(options.dateTimeType) === -1) {
return callback(new Error('DateTimeType should be `Manual` or `NTP`'));
}
this._request({
body: this._envelopeHeader() +
'<SetSystemDateAndTime xmlns="http://www.onvif.org/ver10/device/wsdl">' +
'<DateTimeType>' +
options.dateTimeType +
'</DateTimeType>' +
'<DaylightSavings>' +
( !!options.daylightSavings ) +
'</DaylightSavings>' +
( options.timezone !== undefined ?
'<TimeZone>' +
'<TZ xmlns="http://www.onvif.org/ver10/schema">' +
options.timezone +
'</TZ>' +
'</TimeZone>' : '' ) +
// ( options.dateTime !== undefined && options.dateTime.getDate instanceof Date ?
( options.dateTime !== undefined && options.dateTime instanceof Date ?
'<UTCDateTime>' +
'<Time xmlns="http://www.onvif.org/ver10/schema">' +
'<Hour>' + options.dateTime.getUTCHours() + '</Hour>' +
'<Minute>' + options.dateTime.getUTCMinutes() + '</Minute>' +
'<Second>' + options.dateTime.getUTCSeconds() + '</Second>' +
'</Time>' +
'<Date xmlns="http://www.onvif.org/ver10/schema">' +
'<Year>' + options.dateTime.getUTCFullYear() + '</Year>' +
'<Month>' + (options.dateTime.getUTCMonth() + 1) + '</Month>' +
'<Day>' + options.dateTime.getUTCDate() + '</Day>' +
'</Date>' +
'</UTCDateTime>' : '' ) +
'</SetSystemDateAndTime>' +
this._envelopeFooter()
}, function(err, data, xml) {
if (err || linerase(data).setSystemDateAndTimeResponse !== '') {
return callback.call(this, linerase(data).setSystemDateAndTimeResponse !== ''
? new Error('Wrong `SetSystemDateAndTime` response')
: err, data, xml);
}
//get new system time from device
this.getSystemDateAndTime(callback);
}.bind(this));
};
/**
* Capability list
* @typedef {object} Cam~Capabilities
* @property {object} device Device capabilities
* @property {string} device.XAddr Device service URI
* @property {object} [device.network] Network capabilities
* @property {boolean} device.network.IPFilter Indicates support for IP filtering
* @property {boolean} device.network.zeroConfiguration Indicates support for zeroconf
* @property {boolean} device.network.IPVersion6 Indicates support for IPv6
* @property {boolean} device.network.dynDNS Indicates support for dynamic DNS configuration
* @property {object} [device.system] System capabilities
* @property {boolean} device.system.discoveryResolve Indicates support for WS Discovery resolve requests
* @property {boolean} device.system.discoveryBye Indicates support for WS-Discovery Bye
* @property {boolean} device.system.remoteDiscovery Indicates support for remote discovery
* @property {boolean} device.system.systemBackup Indicates support for system backup through MTOM
* @property {boolean} device.system.systemLogging Indicates support for retrieval of system logging through MTOM
* @property {boolean} device.system.firmwareUpgrade Indicates support for firmware upgrade through MTOM
* @property {boolean} device.system.httpFirmwareUpgrade Indicates support for firmware upgrade through HTTP
* @property {boolean} device.system.httpSystemBackup Indicates support for system backup through HTTP
* @property {boolean} device.system.httpSystemLogging Indicates support for retrieval of system logging through HTTP
* @property {object} [device.IO] I/O capabilities
* @property {number} device.IO.inputConnectors Number of input connectors
* @property {number} device.IO.relayOutputs Number of relay outputs
* @property {object} [device.IO.extension]
* @property {boolean} device.IO.extension.auxiliary
* @property {object} device.IO.extension.auxiliaryCommands
* @property {object} [device.security] Security capabilities
* @property {boolean} device.security.'TLS1.1' Indicates support for TLS 1.1
* @property {boolean} device.security.'TLS1.2' Indicates support for TLS 1.2
* @property {boolean} device.security.onboardKeyGeneration Indicates support for onboard key generation
* @property {boolean} device.security.accessPolicyConfig Indicates support for access policy configuration
* @property {boolean} device.security.'X.509Token' Indicates support for WS-Security X.509 token
* @property {boolean} device.security.SAMLToken Indicates support for WS-Security SAML token
* @property {boolean} device.security.kerberosToken Indicates support for WS-Security Kerberos token
* @property {boolean} device.security.RELToken Indicates support for WS-Security REL token
* @property {object} events Event capabilities
* @property {string} events.XAddr Event service URI
* @property {boolean} events.WSSubscriptionPolicySupport Indicates whether or not WS Subscription policy is supported
* @property {boolean} events.WSPullPointSupport Indicates whether or not WS Pull Point is supported
* @property {boolean} events.WSPausableSubscriptionManagerInterfaceSupport Indicates whether or not WS Pausable Subscription Manager Interface is supported
* @property {object} imaging Imaging capabilities
* @property {string} imaging.XAddr Imaging service URI
* @property {object} media Media capabilities
* @property {string} media.XAddr Media service URI
* @property {object} media.streamingCapabilities Streaming capabilities
* @property {boolean} media.streamingCapabilities.RTPMulticast Indicates whether or not RTP multicast is supported
* @property {boolean} media.streamingCapabilities.RTP_TCP Indicates whether or not RTP over TCP is supported
* @property {boolean} media.streamingCapabilities.RTP_RTSP_TCP Indicates whether or not RTP/RTSP/TCP is supported
* @property {object} media.streamingCapabilities.extension
* @property {object} PTZ PTZ capabilities
* @property {string} PTZ.XAddr PTZ service URI
* @property {object} [extension]
* @property {object} extension.deviceIO DeviceIO capabilities
* @property {string} extension.deviceIO.XAddr DeviceIO service URI
* @property {number} extension.deviceIO.videoSources
* @property {number} extension.deviceIO.videoOutputs
* @property {number} extension.deviceIO.audioSources
* @property {number} extension.deviceIO.audioOutputs
* @property {number} extension.deviceIO.relayOutputs
* @property {object} [extension.extensions]
* @property {object} [extension.extensions.telexCapabilities]
* @property {object} [extension.extensions.scdlCapabilities]
*/
/**
* @callback Cam~GetCapabilitiesCallback
* @property {?Error} error
* @property {Cam~Capabilities} capabilities
* @property {string} xml Raw SOAP response
*/
/**
* Receive cam capabilities
* @param {Cam~GetCapabilitiesCallback} [callback]
*/
Cam.prototype.getCapabilities = function(callback) {
this._request({
body: this._envelopeHeader() +
'<GetCapabilities xmlns="http://www.onvif.org/ver10/device/wsdl">' +
'<Category>All</Category>' +
'</GetCapabilities>' +
this._envelopeFooter()
}, function(err, data, xml) {
if (!err) {
/**
* Device capabilities
* @name Cam#capabilities
* @type {Cam~Capabilities}
*/
this.capabilities = linerase(data[0]['getCapabilitiesResponse'][0]['capabilities'][0]);
// fill Cam#uri property
if (!this.uri) {
/**
* Device service URIs
* @name Cam#uri
* @property {url} [PTZ]
* @property {url} [media]
* @property {url} [imaging]
* @property {url} [events]
* @property {url} [device]
*/
this.uri = {};
}
['PTZ', 'media', 'imaging', 'events', 'device'].forEach(function(name) {
if (this.capabilities[name] && this.capabilities[name].XAddr) {
this.uri[name.toLowerCase()] = this._parseUrl(this.capabilities[name].XAddr);
}
}.bind(this));
// extensions, eg. deviceIO
if (this.capabilities.extension) {
Object.keys(this.capabilities.extension).forEach(function(ext) {
// TODO think about complex extensions like `telexCapabilities` and `scdlCapabilities`
if (this.capabilities.extension[ext].XAddr) {
this.uri[ext] = url.parse(this.capabilities.extension[ext].XAddr);
}
}.bind(this));
}
// HACK for a Profile G NVR that has 'replay' but did not have 'recording' in GetCapabilities
if ((this.uri['replay']) && !this.uri['recording']) {
var tempRecorderXaddr = this.uri['replay'].href.replace('replay','recording');
console.warn("WARNING: Adding " + tempRecorderXaddr + " for bad Profile G device");
this.uri['recording'] = url.parse(tempRecorderXaddr);
}
}
if (callback) {
callback.call(this, err, this.capabilities, xml);
}
}.bind(this));
};
/**
* Returns the capabilities of the device service
* @param [callback]
*/
Cam.prototype.getServiceCapabilities = function(callback) {
this._request({
body: this._envelopeHeader() +
'<GetServiceCapabilities xmlns="http://www.onvif.org/ver10/device/wsdl" />' +
this._envelopeFooter()
}, function(err, data, xml) {
if (!err) {
data = linerase(data);
this.serviceCapabilities = {
network: data.getServiceCapabilitiesResponse.capabilities.network.$
, security: data.getServiceCapabilitiesResponse.capabilities.security.$
, system: data.getServiceCapabilitiesResponse.capabilities.system.$
};
if (data.getServiceCapabilitiesResponse.capabilities.misc) {
this.serviceCapabilities.auxiliaryCommands = data.getServiceCapabilitiesResponse.capabilities.misc.$.AuxiliaryCommands.split(' ');
}
}
if (callback) {
callback.call(this, err, this.serviceCapabilities, xml);
}
}.bind(this));
};
/**
* Active source
* @typedef {object} Cam~ActiveSource
* @property {string} sourceToken video source token
* @property {string} profileToken profile token
* @property {object} [ptz] PTZ-object
* @property {string} ptz.name PTZ configuration name
* @property {string} ptz.token PTZ token
*/
/**
* Get active sources
* @private
*/
Cam.prototype.getActiveSources = function() {
//NVT is a camera with one video source
if (this.videoSources.$) {
this.videoSources = [this.videoSources];
}
//The following code block supports a camera with a single video source
//as well as encoders with multiple sources. By default, the first source is set to the activeSource.
/**
* Default profiles for the device
* @name Cam#defaultProfiles
* @type {Array.<Cam~Profile>}
*/
this.defaultProfiles = [];
/**
* Active video sources
* @name Cam#activeSources
* @type {Array.<Cam~ActiveSource>}
*/
this.activeSources = [];
this.videoSources.forEach(function(videoSource, idx) {
// let's choose first appropriate profile for our video source and make it default
var videoSrcToken = videoSource.$.token
, appropriateProfiles = this.profiles.filter(function(profile) {
return (profile.videoSourceConfiguration
? profile.videoSourceConfiguration.sourceToken === videoSrcToken
: false) && (profile.videoEncoderConfiguration);
});
if (appropriateProfiles.length === 0) {
if (idx === 0) {
throw new Error('Unrecognized configuration');
} else {
return;
}
}
if (idx === 0) {
/**
* Default selected profile for the device
* @name Cam#defaultProfile
* @type {Cam~Profile}
*/
this.defaultProfile = appropriateProfiles[0];
}
this.defaultProfiles[idx] = appropriateProfiles[0];
this.activeSources[idx] = {
sourceToken: videoSource.$.token
, profileToken: this.defaultProfiles[idx].$.token
, encoding: this.defaultProfiles[idx].videoEncoderConfiguration.encoding
, width: this.defaultProfiles[idx].videoEncoderConfiguration.resolution.width
, height: this.defaultProfiles[idx].videoEncoderConfiguration.resolution.height
, fps: this.defaultProfiles[idx].videoEncoderConfiguration.rateControl.frameLimit
, bitrate: this.defaultProfiles[idx].videoEncoderConfiguration.rateControl.bitrateLimit
};
if (idx === 0) {
/**
* Current active video source
* @name Cam#activeSource
* @type {Cam~ActiveSource}
*/
this.activeSource = this.activeSources[idx];
}
if (this.defaultProfiles[idx].PTZConfiguration) {
this.activeSources[idx].ptz = {
name: this.defaultProfiles[idx].PTZConfiguration.name
, token: this.defaultProfiles[idx].PTZConfiguration.$.token
};
/*
TODO Think about it
if (idx === 0) {
this.defaultProfile.PTZConfiguration = this.activeSources[idx].PTZConfiguration;
}*/
}
}.bind(this));
// If we haven't got any active source, send a warning
if (this.activeSources.length === 0) {
/**
* Indicates any warning.
* @event Cam#rawResponse
* @type {string}
*/
this.emit('warning', 'There are no active sources at this device');
}
};
/**
* @typedef {object} Cam~Service
* @property {string} namespace Namespace uri
* @property {string} XAddr Uri for requests
* @property {number} version.minor Minor version
* @property {number} version.major Major version
*/
/**
* @callback Cam~GetServicesCallback
* @property {?Error} error
* @property {Array.<Cam~Service>} services
* @property {string} xml Raw SOAP response
*/
/**
* Receive services
* @param {Cam~GetServicesCallback} [callback]
*/
Cam.prototype.getServices = function(callback) {
this._request({
body: this._envelopeHeader() +
'<GetServices xmlns="http://www.onvif.org/ver10/device/wsdl"><IncludeCapability>true</IncludeCapability></GetServices>' +
this._envelopeFooter()
}, function(err, data, xml) {
if (!err) {
/**
* Supported services and their URLs
* @type {Array.<Cam~Service>}
*/
this.services = linerase(data).getServicesResponse.service;
}
if (callback) {
callback.call(this, err, this.services, xml);
}
}.bind(this));
};
/**
* @typedef {object} Cam~DeviceInformation
* @property {string} manufacturer The manufactor of the device
* @property {string} model The device model
* @property {string} firmwareVersion The firmware version in the device
* @property {string} serialNumber The serial number of the device
* @property {string} hardwareId The hardware ID of the device
*/
/**
* @callback Cam~GetDeviceInformationCallback
* @property {?Error} error
* @property {Cam~DeviceInformation} deviceInformation Device information
* @property {string} xml Raw SOAP response
*/
/**
* Receive device information
* @param {Cam~GetDeviceInformationCallback} [callback]
*/
Cam.prototype.getDeviceInformation = function(callback) {
this._request({
body: this._envelopeHeader() +
'<GetDeviceInformation xmlns="http://www.onvif.org/ver10/device/wsdl"/>' +
this._envelopeFooter()
}, function(err, data, xml) {
if (!err) {
this.deviceInformation = linerase(data).getDeviceInformationResponse;
}
if (callback) {
callback.call(this, err, this.deviceInformation, xml);
}
}.bind(this));
};
/**
* @typedef {object} Cam~HostnameInformation
* @property {boolean} fromDHCP Indicates whether the hostname is obtained from DHCP or not
* @property {string} [name] Indicates the hostname
*/
/**
* @callback Cam~GetHostnameCallback
* @property {?Error} error
* @property {Cam~HostnameInformation} hostnameInformation Hostname information
* @property {string} xml Raw SOAP response
*/
/**
* Receive hostname information
* @param {Cam~GetHostnameCallback} [callback]
*/
Cam.prototype.getHostname = function(callback) {
this._request({
body: this._envelopeHeader() +
'<GetHostname xmlns="http://www.onvif.org/ver10/device/wsdl"/>' +
this._envelopeFooter()
}, function(err, data, xml) {
if (callback) {
callback.call(this, err, err ? null : linerase(data).getHostnameResponse.hostnameInformation, xml);
}
}.bind(this));
};
/**
* @typedef {object} Cam~Scope
* @property {string} scopeDef Indicates if the scope is fixed or configurable
* @property {string} scopeItem Scope item URI
*/
/**
* @callback Cam~getScopesCallback
* @property {?Error} error
* @property {Array<Cam~Scope>} scopes Scopes
* @property {string} xml Raw SOAP response
*/
/**
* Receive the scope parameters of a device
* @param {Cam~getScopesCallback} callback
*/
Cam.prototype.getScopes = function(callback) {
this._request({
body: this._envelopeHeader() +
'<GetScopes xmlns="http://www.onvif.org/ver10/device/wsdl"/>' +
this._envelopeFooter()
}, function(err, data, xml) {
if (!err) {
/**
* Device scopes
* @type {undefined|Array<Cam~Scope>}
*/
this.scopes = linerase(data).getScopesResponse.scopes;
if (this.scopes === undefined) {
this.scopes = [];
} else if (!Array.isArray(this.scopes)) {
this.scopes = [this.scopes];
}
}
if (callback) {
callback.call(this, err, this.scopes, xml);
}
}.bind(this));
};
/**
* Set the scope parameters of a device
* @param {Array<string>} scopes array of scope's uris
* @param {Cam~getScopesCallback} callback
*/
Cam.prototype.setScopes = function(scopes, callback) {
this._request({
body: this._envelopeHeader() +
'<SetScopes xmlns="http://www.onvif.org/ver10/device/wsdl">' +
scopes.map(function(uri) { return '<Scopes>' + uri + '</Scopes>'; }).join('') +
'</SetScopes>' +
this._envelopeFooter()
}, function(err, data, xml) {
if (err || linerase(data).setScopesResponse !== '') {
return callback(linerase(data).setScopesResponse !== '' ? new Error('Wrong `SetScopes` response') : err, data, xml);
}
// get new scopes from device
this.getScopes(callback);
}.bind(this));
};
/**
* /Device/ Reboot the device
* @param {Cam~MessageCallback} callback
*/
Cam.prototype.systemReboot = function(callback) {
this._request({
service: 'deviceIO'
, body: this._envelopeHeader() +
'<SystemReboot xmlns="http://www.onvif.org/ver10/device/wsdl"/>' +
this._envelopeFooter()
}, function(err, res, xml) {
if (!err) {
res = res[0].systemRebootResponse[0].message[0];
}
callback.call(this, err, res, xml);
});
};
/**
* @callback Cam~SetSystemFactoryDefaultCallback
* @property {?Error} error
* @property {null}
* @property {string} xml Raw SOAP response
*/
/**
* Reset camera to factory default
* @param {boolean} [hard=false] Reset network settings
* @param {Cam~SetSystemFactoryDefaultCallback} callback
*/
Cam.prototype.setSystemFactoryDefault = function(hard,callback) {
if (callback === undefined) {
callback = hard;
hard = false;
}
let body = this._envelopeHeader() +
'<SetSystemFactoryDefault xmlns="http://www.onvif.org/ver10/device/wsdl">' +
'<FactoryDefault>' + (hard ? 'Hard' : 'Soft') + '</FactoryDefault>' +
'</SetSystemFactoryDefault>' +
this._envelopeFooter();
this._request({
service: 'device',
body: body,
}, function(err, res, xml) {
if (callback) {
callback.call(this, err, null, xml);
}
});
}
/**
* Generate arguments for digest auth
* @return {{passdigest: *, nonce: (*|String), timestamp: string}}
* @private
*/
Cam.prototype._passwordDigest = function() {
var timestamp = (new Date(Date.now() + (this.timeShift || 0))).toISOString();
var nonce = Buffer.allocUnsafe(16);
nonce.writeUIntLE(Math.ceil(Math.random() * 0x100000000), 0, 4);
nonce.writeUIntLE(Math.ceil(Math.random() * 0x100000000), 4, 4);
nonce.writeUIntLE(Math.ceil(Math.random() * 0x100000000), 8, 4);
nonce.writeUIntLE(Math.ceil(Math.random() * 0x100000000), 12, 4);
var cryptoDigest = crypto.createHash('sha1');
cryptoDigest.update(Buffer.concat([nonce, Buffer.from(timestamp, 'ascii'), Buffer.from(this.password, 'ascii')]));
var passdigest = cryptoDigest.digest('base64');
return {
passdigest: passdigest
, nonce: nonce.toString('base64')
, timestamp: timestamp
};
};
/**
* Envelope header for all SOAP messages
* @property {boolean} [openHeader=false]
* @returns {string}
* @private
*/
Cam.prototype._envelopeHeader = function(openHeader) {
var header = '<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing">' +
'<s:Header>';
// Only insert Security if there is a username and password
if (this.username && this.password) {
var req = this._passwordDigest();
header += '<Security s:mustUnderstand="1" xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">' +
'<UsernameToken>' +
'<Username>' + this.username + '</Username>' +
'<Password Type="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-username-token-profile-1.0#PasswordDigest">' + req.passdigest + '</Password>' +
'<Nonce EncodingType="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-soap-message-security-1.0#Base64Binary">' + req.nonce + '</Nonce>' +
'<Created xmlns="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">' + req.timestamp + '</Created>' +
'</UsernameToken>' +
'</Security>';
}
if (!(openHeader !== undefined && openHeader)) {
header += '</s:Header>' +
'<s:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">';
}
return header;
};
/**
* Envelope footer for all SOAP messages
* @returns {string}
* @private
*/
Cam.prototype._envelopeFooter = function() {
return '</s:Body>' +
'</s:Envelope>';
};
/**
* Parse url with an eye on `preserveAddress` property
* @param {string} address
* @returns {Url}
* @private
*/
Cam.prototype._parseUrl = function(address) {
const parsedAddress = url.parse(address);
// If host for service and default host differs, also if preserve address property set
// we substitute host, hostname and port from settings then rebuild the href using .format
if (this.preserveAddress && this.hostname !== parsedAddress.hostname) {
parsedAddress.hostname = this.hostname;
parsedAddress.host = this.hostname + ':' + this.port;
parsedAddress.port = this.port;
parsedAddress.href = url.format(parsedAddress);
}
return parsedAddress;
};
module.exports = {
Cam: Cam
};
// extending Camera prototype
require('./device' )(Cam);
require('./events')(Cam);
require('./media')(Cam);
require('./ptz')(Cam);
require('./imaging')(Cam);
require('./recording')(Cam);
require('./replay')(Cam);