-
Notifications
You must be signed in to change notification settings - Fork 3
/
twilio.js
8235 lines (7453 loc) · 247 KB
/
twilio.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
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
Twilio = (function(loadedTwilio) {
var Twilio = loadedTwilio || function Twilio() { };
function extend(M) { for (var k in M) Twilio[k] = M[k] }
extend((function(){
var util = require('./twilio/util');
// Hack for determining asset path.
var TWILIO_ROOT = typeof TWILIO_ROOT != "undefined" ? TWILIO_ROOT : (function(){
var prot = location.protocol || "http:",
uri = "//media.twiliocdn.com/sdk/js/client/",
scripts = document.getElementsByTagName("script"),
re = RegExp("(\\w+:)?(\/\/.*)v" + util.getPStreamVersion() + "/(twilio.min.js|twilio.js)");
for (var i = 0; i < scripts.length; i++) {
var match = scripts[i].src.match(re);
if (match) {
prot = (match[1] || prot);
uri = match[2];
break;
}
}
return prot + uri;
})();
// Needed for sounds.
util.setTwilioRoot(TWILIO_ROOT);
// Fin.
var exports = require("./twilio");
return exports;
})());
return Twilio;
})(typeof Twilio !== 'undefined' ? Twilio : null);
},{"./twilio":2,"./twilio/util":19}],2:[function(require,module,exports){
exports.Device = require("./twilio/device").Device;
exports.PStream = require("./twilio/pstream").PStream;
exports.Connection = require("./twilio/connection").Connection;
},{"./twilio/connection":3,"./twilio/device":4,"./twilio/pstream":9}],3:[function(require,module,exports){
var EventEmitter = require('events').EventEmitter;
var Exception = require('./util').Exception;
var log = require('./log');
var Publisher = require('./eventpublisher');
var rtc = require('./rtc');
var RTCMonitor = require('./rtc/monitor');
var twutil = require('./util');
var util = require('util');
var DTMF_INTER_TONE_GAP = 70;
var DTMF_PAUSE_DURATION = 500;
var DTMF_TONE_DURATION = 160;
var METRICS_BATCH_SIZE = 10;
var SAMPLES_TO_IGNORE = 20;
var FEEDBACK_SCORES = [1, 2, 3, 4, 5];
var FEEDBACK_ISSUES = [
'one-way-audio',
'choppy-audio',
'dropped-call',
'audio-latency',
'noisy-call',
'echo'
];
var WARNING_NAMES = {
audioOutputLevel: 'audio-output-level',
audioInputLevel: 'audio-input-level',
packetsLostFraction: 'packet-loss',
jitter: 'jitter',
rtt: 'rtt',
mos: 'mos'
};
var WARNING_PREFIXES = {
min: 'low-',
max: 'high-',
maxDuration: 'constant-'
};
/**
* Constructor for Connections.
*
* @exports Connection as Twilio.Connection
* @memberOf Twilio
* @borrows EventEmitter#addListener as #addListener
* @borrows EventEmitter#emit as #emit
* @borrows EventEmitter#removeListener as #removeListener
* @borrows EventEmitter#hasListener as #hasListener
* @borrows Twilio.mixinLog-log as #log
* @constructor
* @param {object} device The device associated with this connection
* @param {object} message Data to send over the connection
* @param {Connection.Options} [options]
*//**
* @typedef {Object} Connection.Options
* @property {string} [chunder="chunder.prod.twilio.com"] Hostname of chunder server
* @property {boolean} [debug=false] Enable debugging
* @property {boolean} [encrypt=false] Encrypt media
* @property {MediaStream} [mediaStream] Use this MediaStream object
* @property {string} [token] The Twilio capabilities JWT
* @property {string} [callParameters] The call parameters, if this is an incoming
* connection.
*/
function Connection(device, message, options) {
if (!(this instanceof Connection)) {
return new Connection(device, message, options);
}
twutil.monitorEventEmitter('Twilio.Connection', this);
this.device = device;
this.message = message || {};
options = options || {};
var defaults = {
logPrefix: "[Connection]",
mediaStreamFactory: rtc.PeerConnection,
offerSdp: null,
callParameters: { },
debug: false,
encrypt: false,
audioConstraints: device.options['audioConstraints'],
rtcConstraints: device.options['rtcConstraints'],
iceServers: device.options['iceServers']
};
for (var prop in defaults) {
if (prop in options) continue;
options[prop] = defaults[prop];
}
this.options = options;
this.parameters = options.callParameters;
this._status = this.options["offerSdp"] ? "pending" : "closed";
this._direction = this.parameters.CallSid ? 'INCOMING' : 'OUTGOING';
this.sendHangup = true;
log.mixinLog(this, this.options["logPrefix"]);
this.log.enabled = this.options["debug"];
this.log.warnings = this.options['warnings'];
// These are event listeners we need to remove from PStream.
function noop(){}
this._onCancel = noop;
this._onHangup = noop;
this._onAnswer = function(payload) {
if (typeof payload.callsid !== 'undefined') {
self.parameters.CallSid = payload.callsid;
self.mediaStream.callSid = payload.callsid;
}
};
var self = this;
function createDefaultPayload() {
var payload = {
client_name: device._clientName,
platform: rtc.getMediaEngine(),
sdk_version: twutil.getReleaseVersion(),
selected_region: device.options.region
};
if (self.parameters.CallSid && !(/^TJ/.test(self.parameters.CallSid))) {
payload.call_sid = self.parameters.CallSid;
}
if (self.outboundConnectionId) {
payload.temp_call_sid = self.outboundConnectionId;
}
if (device.stream) {
if (device.stream.gateway) {
payload.gateway = device.stream.gateway;
}
if (device.stream.region) {
payload.region = device.stream.region;
}
}
if (self._direction) {
payload.direction = self._direction;
}
return payload;
}
var publisher = this._publisher = new Publisher('twilio-js-sdk', device.token, {
host: device.options.eventgw,
defaultPayload: createDefaultPayload
});
if (options.publishEvents === false) {
publisher.disable();
}
if (this._direction === 'INCOMING') {
publisher.info('connection', 'incoming');
}
var monitor = this._monitor = new RTCMonitor();
// First 10 seconds or so are choppy, so let's not bother with these warnings.
monitor.disableWarnings();
var samples = [];
function createMetricPayload() {
var payload = {
call_sid: self.parameters.CallSid,
client_name: device._clientName,
sdk_version: twutil.getReleaseVersion(),
selected_region: device.options.region
};
if (device.stream) {
if (device.stream.gateway) {
payload.gateway = device.stream.gateway;
}
if (device.stream.region) {
payload.region = device.stream.region;
}
}
if (self._direction) {
payload.direction = self._direction;
}
return payload;
}
function publishMetrics() {
if (samples.length === 0) {
return;
}
publisher.postMetrics(
'quality-metrics-samples', 'metrics-sample', samples.splice(0), createMetricPayload()
);
}
var samplesIgnored = 0;
monitor.on('sample', function(sample) {
// Enable warnings after we've ignored the an initial amount. This is to
// avoid throwing false positive warnings initially.
if (samplesIgnored < SAMPLES_TO_IGNORE) {
samplesIgnored++;
} else if (samplesIgnored === SAMPLES_TO_IGNORE) {
monitor.enableWarnings();
}
samples.push(sample);
if (samples.length >= METRICS_BATCH_SIZE) {
publishMetrics();
}
});
function formatPayloadForEA(warningData) {
var payloadData = { threshold: warningData.threshold.value };
if (warningData.values) {
payloadData.values = warningData.values.map(function(value) {
if (typeof value === 'number') {
return Math.round(value * 100) / 100;
}
return value;
});
} else if (warningData.value) {
payloadData.value = warningData.value;
}
return { data: payloadData };
}
function reemitWarning(wasCleared, warningData) {
var groupPrefix = /^audio/.test(warningData.name) ?
'audio-level-' : 'network-quality-';
var groupSuffix = wasCleared ? '-cleared' : '-raised';
var groupName = groupPrefix + 'warning' + groupSuffix;
var warningPrefix = WARNING_PREFIXES[warningData.threshold.name];
var warningName = warningPrefix + WARNING_NAMES[warningData.name];
// Ignore constant input if the Connection is muted (Expected)
if (warningName === 'constant-audio-input-level' && self.isMuted()) {
return;
}
var level = wasCleared ? 'info' : 'warning';
publisher.post(level, groupName, warningName, formatPayloadForEA(warningData));
}
monitor.on('warning-cleared', reemitWarning.bind(null, true));
monitor.on('warning', reemitWarning.bind(null, false));
/**
* Reference to the Twilio.MediaStream object.
* @type Twilio.MediaStream
*/
this.mediaStream = new this.options["mediaStreamFactory"](
this.options["encrypt"],
this.device);
this.mediaStream.oniceconnectionstatechange = function(state) {
var level = state === 'failed' ? 'error' : 'debug';
publisher.post(level, 'ice-connection-state', state);
};
this.mediaStream.onicegatheringstatechange = function(state) {
publisher.debug('signaling-state', state);
};
this.mediaStream.onsignalingstatechange = function(state) {
publisher.debug('signaling-state', state);
};
var self = this;
this.mediaStream.ondisconnect = function(msg) {
self.log(msg);
publisher.warn('network-quality-warning-raised', 'ice-connectivity-lost', {
message: msg
}, self);
/* (rrowland) This is pretty redundant, but this is intended to match
* the error object that was being returned previously.
* This is removed in 1.4 because we use warning and warning-cleared events
* but there is no parallel in 1.3 and we don't want to break existing
* application logic so we're falling back to error.
*/
self.emit("error", {
code: 31003,
message: msg,
info: {
code: 31003,
message: msg
},
connection: self
});
};
this.mediaStream.onreconnect = function(msg) {
self.log(msg);
publisher.info('network-quality-warning-cleared', 'ice-connectivity-lost', {
message: msg
}, self);
};
this.mediaStream.onerror = function(e) {
if (e.disconnect === true) {
self._disconnect(e.info && e.info.message);
}
var error = {
code: e.info.code,
message: e.info.message || "Error with mediastream",
info: e.info,
connection: self
};
self.log("Received an error from MediaStream:", e);
self.emit("error", error);
};
this.mediaStream.onopen = function() {
// NOTE(mroberts): While this may have been happening in previous
// versions of Chrome, since Chrome 45 we have seen the
// PeerConnection's onsignalingstatechange handler invoked multiple
// times in the same signalingState "stable". When this happens, we
// invoke this onopen function. If we invoke it twice without checking
// for _status "open", we'd accidentally close the PeerConnection.
//
// See <https://code.google.com/p/webrtc/issues/detail?id=4996>.
if (self._status === "open") {
return;
} else if (self._status === "connecting") {
self._status = "open";
self.mediaStream.attachAudio();
self.emit("accept", self);
} else {
// call was probably canceled sometime before this
self.mediaStream.close();
}
};
this.mediaStream.onclose = function() {
self._status = "closed";
if (self.device.sounds.disconnect()) {
self.device.soundcache.play("disconnect");
}
monitor.disable();
publishMetrics();
self.emit("disconnect", self);
};
// temporary call sid to be used for outgoing calls
this.outboundConnectionId = twutil.generateConnectionUUID();
this.pstream = this.device.stream;
this._onCancel = function(payload) {
var callsid = payload.callsid;
if (self.parameters.CallSid == callsid) {
self._status = "closed";
self.emit("cancel");
self.pstream.removeListener("cancel", self._onCancel);
}
};
// NOTE(mroberts): The test "#sendDigits throws error" sets this to `null`.
if (this.pstream)
this.pstream.addListener("cancel", this._onCancel);
this.on('error', function(error) {
publisher.error('connection', 'error', {
code: error.code, message: error.message
});
if (self.pstream && self.pstream.status === 'disconnected') {
cleanupEventListeners(self);
}
});
this.on('disconnect', function() {
cleanupEventListeners(self);
});
return this;
}
util.inherits(Connection, EventEmitter);
/**
* @return {string}
*/
Connection.toString = function() {
return "[Twilio.Connection class]";
};
/**
* @return {string}
*/
Connection.prototype.toString = function() {
return "[Twilio.Connection instance]";
};
Connection.prototype.sendDigits = function(digits) {
if (digits.match(/[^0-9*#w]/)) {
throw new Exception(
"Illegal character passed into sendDigits");
}
var sequence = [];
for(var i = 0; i < digits.length; i++) {
var dtmf = digits[i] != "w" ? "dtmf" + digits[i] : "";
if (dtmf == "dtmf*") dtmf = "dtmfs";
if (dtmf == "dtmf#") dtmf = "dtmfh";
sequence.push([dtmf, 200, 20]);
}
this.device.soundcache.playseq(sequence);
var dtmfSender = this.mediaStream.getOrCreateDTMFSender();
function insertDTMF(dtmfs) {
if (!dtmfs.length) { return; }
var dtmf = dtmfs.shift();
if (dtmf.length) {
dtmfSender.insertDTMF(dtmf, DTMF_TONE_DURATION, DTMF_INTER_TONE_GAP);
}
setTimeout(insertDTMF.bind(null, dtmfs), DTMF_PAUSE_DURATION);
}
if (dtmfSender) {
if (dtmfSender.canInsertDTMF) {
this.log('Sending digits using RTCDTMFSender');
// NOTE(mroberts): We can't just map "w" to "," since
// RTCDTMFSender's pause duration is 2 s and Twilio's is more
// like 500 ms. Instead, we will fudge it with setTimeout.
return insertDTMF(digits.split('w'));
}
this.log('RTCDTMFSender cannot insert DTMF');
}
// send pstream message to send DTMF
this.log('Sending digits over PStream');
if (this.pstream != null && this.pstream.status != "disconnected") {
var payload = { dtmf: digits, callsid: this.parameters.CallSid };
this.pstream.publish("dtmf", payload);
} else {
var payload = { error: {} };
var error = {
code: payload.error.code || 31000,
message: payload.error.message || "Could not send DTMF: Signaling channel is disconnected",
connection: this
};
this.emit("error", error);
}
};
Connection.prototype.status = function() {
return this._status;
};
/**
* Mute incoming audio.
*/
Connection.prototype.mute = function(muteParam) {
if (arguments.length === 0) {
this.log.deprecated('.mute() is deprecated. Please use .mute(true) or .mute(false) to mute or unmute a call instead.');
}
if (typeof muteParam == "function") {
// if handler, register listener
return this.addListener("mute",muteParam);
}
// change state if call results in transition
var wasMuted = this.isMuted();
var self = this;
var callback = function() {
var isMuted = self.isMuted();
if (wasMuted != isMuted) {
self._publisher.info('connection', isMuted ? 'muted' : 'unmuted');
self.emit("mute",isMuted,self);
}
}
if (muteParam == false) {
// if explicitly false, unmute connection
this.mediaStream.attachAudio(callback);
} else {
// if undefined or true, mute connection
this.mediaStream.detachAudio(callback);
}
};
/**
* Check if connection is muted
*/
Connection.prototype.isMuted = function() {
return !this.mediaStream.isAudioAttached();
};
/**
* Unmute (Deprecated)
*/
Connection.prototype.unmute = function() {
this.log.deprecated('.unmute() is deprecated. Please use .mute(false) to unmute a call instead.');
this.mute(false);
};
Connection.prototype.accept = function(handler) {
if (typeof handler == "function") {
return this.addListener("accept", handler);
}
var audioConstraints = handler || this.options.audioConstraints;
var self = this;
this._status = "connecting";
var connect_ = function(err) {
if (self._status != "connecting") {
// call must have been canceled
cleanupEventListeners(self);
self.mediaStream.close();
return;
}
if (err) {
if (err.code === 31208) {
self._publisher.error('get-user-media', 'denied', {
data: {
audioConstraints: audioConstraints,
error: err.error
}
});
} else {
self._publisher.error('get-user-media', 'failed', {
data: {
audioConstraints: audioConstraints,
error: err.error
}
});
}
return self._die(err.message, err.code);
}
self._publisher.info('get-user-media', 'succeeded', {
data: { audioConstraints: audioConstraints }
});
var pairs = [];
for (var key in self.message) {
pairs.push(encodeURIComponent(key) + "=" + encodeURIComponent(self.message[key]));
}
function onLocalAnswer(pc) {
self._publisher.info('connection', 'accepted-by-local');
self._monitor.enable(pc);
}
function onRemoteAnswer(pc) {
self._publisher.info('connection', 'accepted-by-remote');
self._monitor.enable(pc);
}
var params = pairs.join("&");
if (self._direction === 'INCOMING') {
self.mediaStream.answerIncomingCall.call(self.mediaStream, self.parameters.CallSid, self.options["offerSdp"], self.options.rtcConstraints, self.options.iceServers, onLocalAnswer);
} else {
self.pstream.once("answer", self._onAnswer);
self.mediaStream.makeOutgoingCall.call(self.mediaStream, params, self.outboundConnectionId, self.options.rtcConstraints, self.options.iceServers, onRemoteAnswer);
}
self._onHangup = function(payload) {
/**
* see if callsid passed in message matches either callsid or outbound id
* connection should always have either callsid or outbound id
* if no callsid passed hangup anyways
*/
if (payload.callsid && (self.parameters.CallSid || self.outboundConnectionId)) {
if (payload.callsid != self.parameters.CallSid && payload.callsid != self.outboundConnectionId) {
return;
}
} else if (payload.callsid) {
// hangup is for another connection
return;
}
self.log("Received HANGUP from gateway");
if (payload.error) {
var error = {
code: payload.error.code || 31000,
message: payload.error.message || "Error sent from gateway in HANGUP",
connection: self
};
self.log("Received an error from the gateway:", error);
self.emit("error", error);
}
self.sendHangup = false;
self._publisher.info('connection', 'disconnected-by-remote');
self._disconnect();
cleanupEventListeners(self);
};
self.pstream.addListener("hangup", self._onHangup);
};
this.mediaStream.openHelper(connect_, audioConstraints);
};
Connection.prototype.reject = function(handler) {
if (typeof handler == "function") {
return this.addListener("reject", handler);
}
if (this._status == "pending") {
var payload = { callsid: this.parameters.CallSid }
this.pstream.publish("reject", payload);
this.emit("reject");
this.mediaStream.reject(this.parameters.CallSid);
this._publisher.info('connection', 'rejected-by-local');
}
};
Connection.prototype.ignore = function(handler) {
if (typeof handler == "function") {
return this.addListener("cancel", handler);
}
if (this._status == "pending") {
this._status = "closed";
this.emit("cancel");
this.mediaStream.ignore(this.parameters.CallSid);
this._publisher.info('connection', 'ignored-by-local');
}
};
Connection.prototype.cancel = function(handler) {
this.log.deprecated('.cancel() is deprecated. Please use .ignore() instead.');
this.ignore(handler);
};
Connection.prototype.disconnect = function(handler) {
if (typeof handler === "function") {
return this.addListener("disconnect", handler);
}
this._publisher.info('connection', 'disconnected-by-local');
this._disconnect();
};
Connection.prototype._disconnect = function(message) {
message = typeof message === 'string' ? message : null;
if (this._status == "open" || this._status == "connecting") {
this.log("Disconnecting...");
// send pstream hangup message
if (this.pstream != null && this.pstream.status != "disconnected" && this.sendHangup) {
var callId = this.parameters.CallSid || this.outboundConnectionId;
if (callId) {
var payload = { callsid: callId };
if (message) {
payload.message = message;
}
this.pstream.publish("hangup", payload);
}
}
cleanupEventListeners(this);
this.mediaStream.close();
}
};
Connection.prototype.error = function(handler) {
if (typeof handler == "function") {
return this.addListener("error", handler);
}
};
Connection.prototype._die = function(message,code) {
this.emit("error", { message: message, code: code });
this._disconnect();
};
function cleanupEventListeners(connection) {
function cleanup() {
connection.pstream.removeListener('answer', connection._onAnswer);
connection.pstream.removeListener('cancel', connection._onCancel);
connection.pstream.removeListener('hangup', connection._onHangup);
}
cleanup();
// This is kind of a hack, but it lets us avoid rewriting more code.
// Basically, there's a sequencing problem with the way PeerConnection raises
// the
//
// Cannot establish connection. Client is disconnected
//
// error in Connection#accept. It calls PeerConnection#onerror, which emits
// the error event on Connection. An error handler on Connection then calls
// cleanupEventListeners, but then control returns to Connection#accept. It's
// at this point that we add a listener for the answer event that never gets
// removed. setTimeout will allow us to rerun cleanup again, _after_
// Connection#accept returns.
setTimeout(cleanup, 0);
}
exports.Connection = Connection;
},{"./eventpublisher":5,"./log":7,"./rtc":11,"./rtc/monitor":12,"./util":19,"events":21,"util":37}],4:[function(require,module,exports){
var EventEmitter = require('events').EventEmitter;
var util = require('util');
var log = require("./log");
var twutil = require("./util");
var rtc = require("./rtc");
var Options = require("./options").Options;
var Sound = require("./sound").Sound;
var SoundCache = require('./soundcache').SoundCache;
var Connection = require('./connection').Connection;
var PStream = require('./pstream').PStream;
var REG_INTERVAL = 30000;
/**
* Constructor for Device objects.
*
* @exports Device as Twilio.Device
* @memberOf Twilio
* @borrows EventEmitter#addListener as #addListener
* @borrows EventEmitter#emit as #emit
* @borrows EventEmitter#hasListener #hasListener
* @borrows EventEmitter#removeListener as #removeListener
* @borrows Twilio.mixinLog-log as #log
* @constructor
* @param {string} token The Twilio capabilities token
* @param {object} [options]
* @config {boolean} [debug=false]
*/
function Device(token, options) {
if (!rtc.enabled()) {
throw new twutil.Exception('twilio.js 1.3 requires WebRTC/ORTC browser support. '
+ 'For more information, see <https://www.twilio.com/docs/api/client/twilio-js>. '
+ 'If you have any questions about this announcement, please contact '
+ 'Twilio Support at <help@twilio.com>.');
}
if (!(this instanceof Device)) {
return new Device(token, options);
}
twutil.monitorEventEmitter('Twilio.Device', this);
if (!token) {
throw new twutil.Exception("Capability token is not valid or missing.");
}
// copy options
var origOptions = {};
for (i in options) {
origOptions[i] = options[i];
}
var defaults = {
logPrefix: "[Device]",
chunderw: "chunderw-vpc-gll.twilio.com",
eventgw: "eventgw.twilio.com",
soundCacheFactory: SoundCache,
soundFactory: Sound,
connectionFactory: Connection,
pStreamFactory: PStream,
noRegister: false,
encrypt: false,
closeProtection: false,
secureSignaling: true,
warnings: true,
audioConstraints: true,
iceServers: [],
region: "gll",
dscp: true,
sounds: { }
};
options = options || {};
var chunderw = options['chunderw'];
for (var prop in defaults) {
if (prop in options) continue;
options[prop] = defaults[prop];
}
if (options.dscp) {
options.rtcConstraints = {
optional: [
{
googDscp: true
}
]
};
} else {
options.rtcConstraints = {};
}
this.options = options;
this.token = token;
this._status = "offline";
this._region = "offline";
this.connections = [];
this.sounds = new Options({
incoming: true,
outgoing: true,
disconnect: true
});
log.mixinLog(this, this.options["logPrefix"]);
this.log.enabled = this.options["debug"];
var regions = {
'gll': 'chunderw-vpc-gll.twilio.com',
'au1': 'chunderw-vpc-gll-au1.twilio.com',
'br1': 'chunderw-vpc-gll-br1.twilio.com',
'ie1': 'chunderw-vpc-gll-ie1.twilio.com',
'jp1': 'chunderw-vpc-gll-jp1.twilio.com',
'sg1': 'chunderw-vpc-gll-sg1.twilio.com',
'us1': 'chunderw-vpc-gll-us1.twilio.com'
};
var deprecatedRegions = {
'au': 'au1',
'br': 'br1',
'ie': 'ie1',
'jp': 'jp1',
'sg': 'sg1',
'us-va': 'us1',
'us-or': 'us1'
};
var region = options['region'].toLowerCase();
if (region in deprecatedRegions) {
this.log.deprecated('Region ' + region + ' is deprecated, please use ' + deprecatedRegions[region] + '.');
region = deprecatedRegions[region];
}
if (!(region in regions)) {
throw new twutil.Exception('Region ' + options['region'] + ' is invalid. ' +
'Valid values are: ' + Object.keys(regions).join(', '));
}
options['chunderw'] = chunderw || regions[region];
this.soundcache = this.options["soundCacheFactory"]();
// NOTE(mroberts): Node workaround.
if (typeof document === 'undefined')
var a = {};
else
var a = document.createElement("audio");
canPlayMp3 = false;
try {
canPlayMp3 = !!(a.canPlayType && a.canPlayType('audio/mpeg').replace(/no/, ''));
}
catch (e) {
}
canPlayVorbis = false;
try {
canPlayVorbis = !!(a.canPlayType && a.canPlayType('audio/ogg;codecs="vorbis"').replace(/no/, ''));
}
catch (e) {
}
var ext = "mp3";
if (canPlayVorbis && !canPlayMp3) {
ext = "ogg";
}
var defaultSounds = {
incoming: { filename: 'incoming', loop: true },
outgoing: { filename: 'outgoing', maxDuration: 3000 },
disconnect: { filename: 'disconnect', maxDuration: 3000 },
dtmf1: { filename: 'dtmf-1', maxDuration: 1000 },
dtmf2: { filename: 'dtmf-2', maxDuration: 1000 },
dtmf3: { filename: 'dtmf-3', maxDuration: 1000 },
dtmf4: { filename: 'dtmf-4', maxDuration: 1000 },
dtmf5: { filename: 'dtmf-5', maxDuration: 1000 },
dtmf6: { filename: 'dtmf-6', maxDuration: 1000 },
dtmf7: { filename: 'dtmf-7', maxDuration: 1000 },
dtmf8: { filename: 'dtmf-8', maxDuration: 1000 },
dtmf9: { filename: 'dtmf-9', maxDuration: 1000 },
dtmf0: { filename: 'dtmf-0', maxDuration: 1000 },
dtmfs: { filename: 'dtmf-star', maxDuration: 1000 },
dtmfh: { filename: 'dtmf-hash', maxDuration: 1000 }
};
var base = twutil.getTwilioRoot() + 'sounds/releases/' + twutil.getSoundVersion() + '/';
for (var name in defaultSounds) {
var soundDef = defaultSounds[name];
var sound = this.options.soundFactory(soundDef);
var defaultUrl = base + soundDef.filename + '.' + ext;
sound.load(defaultUrl);
this.soundcache.add(name, sound);
}
// Minimum duration for incoming ring
this.soundcache.envelope("incoming", { release: 2000 });
var device = this;
this.addListener("incoming", function(connection) {
connection.once("accept", function() {
device.soundcache.stop("incoming");
});
connection.once("cancel", function() {
device.soundcache.stop("incoming");
});
connection.once("error", function() {
device.soundcache.stop("incoming");
});
connection.once("reject", function() {
device.soundcache.stop("incoming");
});
if (device.sounds.incoming()) {
device.soundcache.play("incoming", 0, 1000);
}
});
// setup flag for allowing presence for media types
this.mediaPresence = { audio: !this.options["noRegister"] };
// setup stream
this.register(this.token);
var self = this;
var closeProtection = this.options["closeProtection"];
if (closeProtection) {
var confirmClose = function(event) {
if (device._status == "busy" || self.connections[0]) {
var defaultMsg = "A call is currently in-progress. Leaving or reloading this page will end the call.";
var confirmationMsg = closeProtection == true ? defaultMsg : closeProtection;
(event || window.event).returnValue = confirmationMsg;
return confirmationMsg;
}
};
if (typeof window !== 'undefined') {
if (window.addEventListener) {
window.addEventListener("beforeunload", confirmClose);
} else if (window.attachEvent) {
window.attachEvent("onbeforeunload", confirmClose);
}
}
}
// close connections on unload
var onClose = function() {
device.disconnectAll();
}
if (typeof window !== 'undefined') {
if (window.addEventListener) {
window.addEventListener("unload", onClose);
} else if (window.attachEvent) {
window.attachEvent("onunload", onClose);
}
}
// NOTE(mroberts): EventEmitter requires that we catch all errors.
this.on('error', function(){});
return this;
}
util.inherits(Device, EventEmitter);
function makeConnection(device, params, options) {
var defaults = {
publishEvents: device.options.publishEvents,
debug: device.options.debug,
encrypt: device.options.encrypt,
warnings: device.options.warnings
};
options = options || {};
for (var prop in defaults) {
if (prop in options) continue;
options[prop] = defaults[prop];
}
var connection = device.options["connectionFactory"](device, params, options);