@signalwire/js 1.3.0-dev.0 → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (65) hide show
  1. package/README.md +4 -2
  2. package/dist/esm/common/src/BaseSession.d.ts +8 -13
  3. package/dist/esm/common/src/BaseSession.js +33 -46
  4. package/dist/esm/common/src/BrowserSession.d.ts +20 -57
  5. package/dist/esm/common/src/BrowserSession.js +91 -359
  6. package/dist/esm/common/src/messages/Verto.d.ts +1 -10
  7. package/dist/esm/common/src/messages/Verto.js +1 -16
  8. package/dist/esm/common/src/messages/verto/Login.d.ts +1 -13
  9. package/dist/esm/common/src/messages/verto/Login.js +2 -5
  10. package/dist/esm/common/src/services/BroadcastHandler.js +3 -2
  11. package/dist/esm/common/src/services/Handler.d.ts +8 -9
  12. package/dist/esm/common/src/services/Handler.js +38 -41
  13. package/dist/esm/common/src/util/constants/index.d.ts +0 -1
  14. package/dist/esm/common/src/util/constants/index.js +0 -1
  15. package/dist/esm/common/src/util/helpers.d.ts +9 -2
  16. package/dist/esm/common/src/util/helpers.js +11 -6
  17. package/dist/esm/common/src/util/interfaces.d.ts +55 -20
  18. package/dist/esm/common/src/util/logger.js +1 -4
  19. package/dist/esm/common/src/util/webrtc/index.d.ts +1 -6
  20. package/dist/esm/common/src/util/webrtc/index.js +2 -63
  21. package/dist/esm/common/src/webrtc/BaseCall.d.ts +76 -0
  22. package/dist/esm/common/src/webrtc/BaseCall.js +701 -0
  23. package/dist/esm/common/src/webrtc/Call.d.ts +5 -5
  24. package/dist/esm/common/src/webrtc/Call.js +15 -34
  25. package/dist/esm/common/src/webrtc/CantinaAuth.d.ts +13 -8
  26. package/dist/esm/common/src/webrtc/CantinaAuth.js +18 -24
  27. package/dist/esm/common/src/webrtc/LayoutHandler.d.ts +3 -0
  28. package/dist/esm/common/src/webrtc/LayoutHandler.js +36 -0
  29. package/dist/esm/common/src/webrtc/Peer.d.ts +21 -0
  30. package/dist/esm/common/src/webrtc/Peer.js +145 -0
  31. package/dist/esm/common/src/webrtc/VertoHandler.d.ts +11 -2
  32. package/dist/esm/common/src/webrtc/VertoHandler.js +187 -147
  33. package/dist/esm/common/src/webrtc/constants.d.ts +12 -28
  34. package/dist/esm/common/src/webrtc/constants.js +11 -34
  35. package/dist/esm/common/src/webrtc/helpers.d.ts +20 -18
  36. package/dist/esm/common/src/webrtc/helpers.js +177 -162
  37. package/dist/esm/common/src/webrtc/interfaces.d.ts +51 -209
  38. package/dist/esm/js/index.d.ts +1 -3
  39. package/dist/esm/js/index.js +1 -2
  40. package/dist/esm/js/src/SignalWire.d.ts +2 -0
  41. package/dist/esm/js/src/SignalWire.js +13 -0
  42. package/dist/esm/js/src/Verto.d.ts +2 -8
  43. package/dist/esm/js/src/Verto.js +14 -50
  44. package/dist/index.min.js +2 -2
  45. package/package.json +13 -14
  46. package/dist/esm/common/src/webrtc/ChatChannelHandler.d.ts +0 -5
  47. package/dist/esm/common/src/webrtc/ChatChannelHandler.js +0 -22
  48. package/dist/esm/common/src/webrtc/Conference.d.ts +0 -15
  49. package/dist/esm/common/src/webrtc/Conference.js +0 -68
  50. package/dist/esm/common/src/webrtc/ConferenceListChannelHandler.d.ts +0 -5
  51. package/dist/esm/common/src/webrtc/ConferenceListChannelHandler.js +0 -77
  52. package/dist/esm/common/src/webrtc/InfoChannelHandler.d.ts +0 -7
  53. package/dist/esm/common/src/webrtc/InfoChannelHandler.js +0 -85
  54. package/dist/esm/common/src/webrtc/LaChannelHandler.d.ts +0 -5
  55. package/dist/esm/common/src/webrtc/LaChannelHandler.js +0 -58
  56. package/dist/esm/common/src/webrtc/ModChannelHandler.d.ts +0 -71
  57. package/dist/esm/common/src/webrtc/ModChannelHandler.js +0 -267
  58. package/dist/esm/common/src/webrtc/RTCPeer.d.ts +0 -51
  59. package/dist/esm/common/src/webrtc/RTCPeer.js +0 -556
  60. package/dist/esm/common/src/webrtc/WebRTCCall.d.ts +0 -182
  61. package/dist/esm/common/src/webrtc/WebRTCCall.js +0 -784
  62. package/dist/esm/common/src/webrtc/deviceHelpers.d.ts +0 -18
  63. package/dist/esm/common/src/webrtc/deviceHelpers.js +0 -113
  64. package/dist/esm/common/src/webrtc/sdpHelpers.d.ts +0 -3
  65. package/dist/esm/common/src/webrtc/sdpHelpers.js +0 -56
@@ -0,0 +1,701 @@
1
+ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
2
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
3
+ return new (P || (P = Promise))(function (resolve, reject) {
4
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
5
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
6
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
7
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
8
+ });
9
+ };
10
+ import { v4 as uuidv4 } from 'uuid';
11
+ import logger from '../util/logger';
12
+ import { Invite, Answer, Attach, Bye, Modify, Info } from '../messages/Verto';
13
+ import Peer from './Peer';
14
+ import { SwEvent } from '../util/constants';
15
+ import { State, DEFAULT_CALL_OPTIONS, ConferenceAction, Role, PeerType, VertoMethod, NOTIFICATION_TYPE, Direction } from './constants';
16
+ import { trigger, register, deRegister } from '../services/Handler';
17
+ import { sdpStereoHack, sdpMediaOrderHack, checkSubscribeResponse, enableAudioTracks, disableAudioTracks, toggleAudioTracks, enableVideoTracks, disableVideoTracks, toggleVideoTracks } from './helpers';
18
+ import { objEmpty, mutateLiveArrayData, isFunction } from '../util/helpers';
19
+ import { attachMediaStream, detachMediaStream, sdpToJsonHack, stopStream, getUserMedia, setMediaElementSinkId } from '../util/webrtc';
20
+ import { MCULayoutEventHandler } from './LayoutHandler';
21
+ export default class BaseCall {
22
+ constructor(session, opts) {
23
+ this.session = session;
24
+ this.id = '';
25
+ this.state = State[State.New];
26
+ this.prevState = '';
27
+ this.channels = [];
28
+ this.role = Role.Participant;
29
+ this.extension = null;
30
+ this._state = State.New;
31
+ this._prevState = State.New;
32
+ this.gotAnswer = false;
33
+ this.gotEarly = false;
34
+ this._lastSerno = 0;
35
+ this._targetNodeId = null;
36
+ this._iceTimeout = null;
37
+ this._iceDone = false;
38
+ this._checkConferenceSerno = (serno) => {
39
+ const check = (serno < 0) || (!this._lastSerno || (this._lastSerno && serno === (this._lastSerno + 1)));
40
+ if (check && serno >= 0) {
41
+ this._lastSerno = serno;
42
+ }
43
+ return check;
44
+ };
45
+ const { iceServers, speaker: speakerId, micId, micLabel, camId, camLabel, localElement, remoteElement, mediaConstraints: { audio, video } } = session;
46
+ this.options = Object.assign({}, DEFAULT_CALL_OPTIONS, { audio, video, iceServers, localElement, remoteElement, micId, micLabel, camId, camLabel, speakerId }, opts);
47
+ this._onMediaError = this._onMediaError.bind(this);
48
+ this._init();
49
+ }
50
+ get nodeId() {
51
+ return this._targetNodeId;
52
+ }
53
+ set nodeId(what) {
54
+ this._targetNodeId = what;
55
+ }
56
+ get localStream() {
57
+ return this.options.localStream;
58
+ }
59
+ get remoteStream() {
60
+ return this.options.remoteStream;
61
+ }
62
+ get memberChannel() {
63
+ return `conference-member.${this.id}`;
64
+ }
65
+ invite() {
66
+ this.direction = Direction.Outbound;
67
+ this.peer = new Peer(PeerType.Offer, this.options);
68
+ this._registerPeerEvents();
69
+ }
70
+ answer(params) {
71
+ if (params && (params === null || params === void 0 ? void 0 : params.iceTransportPolicy)) {
72
+ this.options.iceTransportPolicy = params === null || params === void 0 ? void 0 : params.iceTransportPolicy;
73
+ }
74
+ this.direction = Direction.Inbound;
75
+ this.peer = new Peer(PeerType.Answer, this.options);
76
+ this._registerPeerEvents();
77
+ }
78
+ hangup(params = {}, execute = true) {
79
+ this.cause = params.cause || 'NORMAL_CLEARING';
80
+ this.causeCode = params.causeCode || 16;
81
+ this.setState(State.Hangup);
82
+ const _close = () => {
83
+ this.peer ? this.peer.instance.close() : null;
84
+ this.setState(State.Destroy);
85
+ };
86
+ if (execute) {
87
+ const bye = new Bye({ sessid: this.session.sessionid, dialogParams: this.options });
88
+ this._execute(bye)
89
+ .catch(error => logger.error('verto.bye failed!', error))
90
+ .then(_close.bind(this));
91
+ }
92
+ else {
93
+ _close();
94
+ }
95
+ }
96
+ transfer(destination) {
97
+ const msg = new Modify({ sessid: this.session.sessionid, action: 'transfer', destination, dialogParams: this.options });
98
+ this._execute(msg);
99
+ }
100
+ replace(replaceCallID) {
101
+ const msg = new Modify({ sessid: this.session.sessionid, action: 'replace', replaceCallID, dialogParams: this.options });
102
+ this._execute(msg);
103
+ }
104
+ hold() {
105
+ const msg = new Modify({ sessid: this.session.sessionid, action: 'hold', dialogParams: this.options });
106
+ return this._execute(msg)
107
+ .then(this._handleChangeHoldStateSuccess.bind(this))
108
+ .catch(this._handleChangeHoldStateError.bind(this));
109
+ }
110
+ unhold() {
111
+ const msg = new Modify({ sessid: this.session.sessionid, action: 'unhold', dialogParams: this.options });
112
+ return this._execute(msg)
113
+ .then(this._handleChangeHoldStateSuccess.bind(this))
114
+ .catch(this._handleChangeHoldStateError.bind(this));
115
+ }
116
+ toggleHold() {
117
+ const msg = new Modify({ sessid: this.session.sessionid, action: 'toggleHold', dialogParams: this.options });
118
+ return this._execute(msg)
119
+ .then(this._handleChangeHoldStateSuccess.bind(this))
120
+ .catch(this._handleChangeHoldStateError.bind(this));
121
+ }
122
+ dtmf(dtmf) {
123
+ const msg = new Info({ sessid: this.session.sessionid, dtmf, dialogParams: this.options });
124
+ this._execute(msg);
125
+ }
126
+ message(to, body) {
127
+ const msg = { from: this.session.options.login, to, body };
128
+ const info = new Info({ sessid: this.session.sessionid, msg, dialogParams: this.options });
129
+ this._execute(info);
130
+ }
131
+ muteAudio() {
132
+ disableAudioTracks(this.options.localStream);
133
+ }
134
+ unmuteAudio() {
135
+ enableAudioTracks(this.options.localStream);
136
+ }
137
+ toggleAudioMute() {
138
+ toggleAudioTracks(this.options.localStream);
139
+ }
140
+ setAudioInDevice(deviceId) {
141
+ return __awaiter(this, void 0, void 0, function* () {
142
+ const { instance } = this.peer;
143
+ const sender = instance.getSenders().find(({ track: { kind } }) => kind === 'audio');
144
+ if (sender) {
145
+ const newStream = yield getUserMedia({ audio: { deviceId: { exact: deviceId } } });
146
+ const audioTrack = newStream.getAudioTracks()[0];
147
+ sender.replaceTrack(audioTrack);
148
+ this.options.micId = deviceId;
149
+ const { localStream } = this.options;
150
+ localStream.getAudioTracks().forEach(t => t.stop());
151
+ localStream.getVideoTracks().forEach(t => newStream.addTrack(t));
152
+ this.options.localStream = newStream;
153
+ }
154
+ });
155
+ }
156
+ muteVideo() {
157
+ disableVideoTracks(this.options.localStream);
158
+ }
159
+ unmuteVideo() {
160
+ enableVideoTracks(this.options.localStream);
161
+ }
162
+ toggleVideoMute() {
163
+ toggleVideoTracks(this.options.localStream);
164
+ }
165
+ setVideoDevice(deviceId) {
166
+ return __awaiter(this, void 0, void 0, function* () {
167
+ const { instance } = this.peer;
168
+ const sender = instance.getSenders().find(({ track: { kind } }) => kind === 'video');
169
+ if (sender) {
170
+ const newStream = yield getUserMedia({ video: { deviceId: { exact: deviceId } } });
171
+ const videoTrack = newStream.getVideoTracks()[0];
172
+ sender.replaceTrack(videoTrack);
173
+ const { localElement, localStream } = this.options;
174
+ attachMediaStream(localElement, newStream);
175
+ this.options.camId = deviceId;
176
+ localStream.getAudioTracks().forEach(t => newStream.addTrack(t));
177
+ localStream.getVideoTracks().forEach(t => t.stop());
178
+ this.options.localStream = newStream;
179
+ }
180
+ });
181
+ }
182
+ deaf() {
183
+ disableAudioTracks(this.options.remoteStream);
184
+ }
185
+ undeaf() {
186
+ enableAudioTracks(this.options.remoteStream);
187
+ }
188
+ toggleDeaf() {
189
+ toggleAudioTracks(this.options.remoteStream);
190
+ }
191
+ setState(state) {
192
+ this._prevState = this._state;
193
+ this._state = state;
194
+ this.state = State[this._state].toLowerCase();
195
+ this.prevState = State[this._prevState].toLowerCase();
196
+ logger.info(`Call ${this.id} state change from ${this.prevState} to ${this.state}`);
197
+ this._dispatchNotification({ type: NOTIFICATION_TYPE.callUpdate, call: this });
198
+ switch (state) {
199
+ case State.Purge:
200
+ this.hangup({ cause: 'PURGE', causeCode: '01' }, false);
201
+ break;
202
+ case State.Active: {
203
+ setTimeout(() => {
204
+ const { remoteElement, speakerId } = this.options;
205
+ if (remoteElement && speakerId) {
206
+ setMediaElementSinkId(remoteElement, speakerId);
207
+ }
208
+ }, 0);
209
+ break;
210
+ }
211
+ case State.Destroy:
212
+ this._finalize();
213
+ break;
214
+ }
215
+ }
216
+ handleMessage(msg) {
217
+ const { method, params } = msg;
218
+ switch (method) {
219
+ case VertoMethod.Answer: {
220
+ this.gotAnswer = true;
221
+ if (this._state >= State.Active) {
222
+ return;
223
+ }
224
+ if (this._state >= State.Early) {
225
+ this.setState(State.Active);
226
+ }
227
+ if (!this.gotEarly) {
228
+ this._onRemoteSdp(params.sdp);
229
+ }
230
+ break;
231
+ }
232
+ case VertoMethod.Media: {
233
+ if (this._state >= State.Early) {
234
+ return;
235
+ }
236
+ this.gotEarly = true;
237
+ this._onRemoteSdp(params.sdp);
238
+ break;
239
+ }
240
+ case VertoMethod.Display:
241
+ case VertoMethod.Attach: {
242
+ const { display_name: displayName, display_number: displayNumber, display_direction } = params;
243
+ this.extension = displayNumber;
244
+ const displayDirection = display_direction === Direction.Inbound ? Direction.Outbound : Direction.Inbound;
245
+ const notification = { type: NOTIFICATION_TYPE[method], call: this, displayName, displayNumber, displayDirection };
246
+ if (!trigger(SwEvent.Notification, notification, this.id)) {
247
+ trigger(SwEvent.Notification, notification, this.session.uuid);
248
+ }
249
+ break;
250
+ }
251
+ case VertoMethod.Info:
252
+ case VertoMethod.Event: {
253
+ const notification = Object.assign(Object.assign({}, params), { type: NOTIFICATION_TYPE.generic, call: this });
254
+ if (!trigger(SwEvent.Notification, notification, this.id)) {
255
+ trigger(SwEvent.Notification, notification, this.session.uuid);
256
+ }
257
+ break;
258
+ }
259
+ case VertoMethod.Bye:
260
+ this.hangup(params, false);
261
+ break;
262
+ }
263
+ }
264
+ handleConferenceUpdate(packet, initialPvtData) {
265
+ return __awaiter(this, void 0, void 0, function* () {
266
+ if (!this._checkConferenceSerno(packet.wireSerno) && packet.name !== initialPvtData.laName) {
267
+ logger.error('ConferenceUpdate invalid wireSerno or packet name:', packet);
268
+ return 'INVALID_PACKET';
269
+ }
270
+ const { action, data, hashKey: callId = String(this._lastSerno), arrIndex: index } = packet;
271
+ switch (action) {
272
+ case 'bootObj': {
273
+ this._lastSerno = 0;
274
+ const { chatID, chatChannel, infoChannel, modChannel, laName, conferenceMemberID, role } = initialPvtData;
275
+ this._dispatchConferenceUpdate({ action: ConferenceAction.Join, conferenceName: laName, participantId: Number(conferenceMemberID), role });
276
+ if (chatChannel) {
277
+ yield this._subscribeConferenceChat(chatChannel);
278
+ }
279
+ if (infoChannel) {
280
+ yield this._subscribeConferenceInfo(infoChannel);
281
+ }
282
+ if (modChannel && role === Role.Moderator) {
283
+ yield this._subscribeConferenceModerator(modChannel);
284
+ }
285
+ const participants = [];
286
+ for (const i in data) {
287
+ participants.push(Object.assign({ callId: data[i][0], index: Number(i) }, mutateLiveArrayData(data[i][1])));
288
+ }
289
+ this._dispatchConferenceUpdate({ action: ConferenceAction.Bootstrap, participants });
290
+ break;
291
+ }
292
+ case 'add': {
293
+ this._dispatchConferenceUpdate(Object.assign({ action: ConferenceAction.Add, callId, index }, mutateLiveArrayData(data)));
294
+ break;
295
+ }
296
+ case 'modify':
297
+ this._dispatchConferenceUpdate(Object.assign({ action: ConferenceAction.Modify, callId, index }, mutateLiveArrayData(data)));
298
+ break;
299
+ case 'del':
300
+ this._dispatchConferenceUpdate(Object.assign({ action: ConferenceAction.Delete, callId, index }, mutateLiveArrayData(data)));
301
+ break;
302
+ case 'clear':
303
+ this._dispatchConferenceUpdate({ action: ConferenceAction.Clear });
304
+ break;
305
+ default:
306
+ this._dispatchConferenceUpdate({ action, data, callId, index });
307
+ break;
308
+ }
309
+ });
310
+ }
311
+ _addChannel(channel) {
312
+ if (!this.channels.includes(channel)) {
313
+ this.channels.push(channel);
314
+ }
315
+ const protocol = this.session.relayProtocol;
316
+ if (this.session._existsSubscription(protocol, channel)) {
317
+ this.session.subscriptions[protocol][channel] = Object.assign(Object.assign({}, this.session.subscriptions[protocol][channel]), { callId: this.id });
318
+ }
319
+ }
320
+ _subscribeConferenceChat(channel) {
321
+ return __awaiter(this, void 0, void 0, function* () {
322
+ const tmp = {
323
+ nodeId: this.nodeId,
324
+ channels: [channel],
325
+ handler: (params) => {
326
+ const { direction, from: participantNumber, fromDisplay: participantName, message: messageText, type: messageType } = params.data;
327
+ this._dispatchConferenceUpdate({ action: ConferenceAction.ChatMessage, direction, participantNumber, participantName, messageText, messageType, messageId: params.eventSerno });
328
+ }
329
+ };
330
+ const response = yield this.session.vertoSubscribe(tmp)
331
+ .catch(error => {
332
+ logger.error('ConfChat subscription error:', error);
333
+ });
334
+ if (checkSubscribeResponse(response, channel)) {
335
+ this._addChannel(channel);
336
+ Object.defineProperties(this, {
337
+ sendChatMessage: {
338
+ configurable: true,
339
+ value: (message, type) => {
340
+ this.session.vertoBroadcast({ nodeId: this.nodeId, channel, data: { action: 'send', message, type } });
341
+ }
342
+ }
343
+ });
344
+ }
345
+ });
346
+ }
347
+ _subscribeConferenceInfo(channel) {
348
+ return __awaiter(this, void 0, void 0, function* () {
349
+ const tmp = {
350
+ nodeId: this.nodeId,
351
+ channels: [channel],
352
+ handler: (params) => {
353
+ const { eventData } = params;
354
+ switch (eventData.contentType) {
355
+ case 'layout-info':
356
+ eventData.callID = this.id;
357
+ MCULayoutEventHandler(this.session, eventData);
358
+ break;
359
+ default:
360
+ logger.error('Conference-Info unknown contentType', params);
361
+ }
362
+ }
363
+ };
364
+ const response = yield this.session.vertoSubscribe(tmp)
365
+ .catch(error => {
366
+ logger.error('ConfInfo subscription error:', error);
367
+ });
368
+ if (checkSubscribeResponse(response, channel)) {
369
+ this._addChannel(channel);
370
+ }
371
+ });
372
+ }
373
+ _confControl(channel, params = {}) {
374
+ const data = Object.assign({ application: 'conf-control', callID: this.id, value: null }, params);
375
+ this.session.vertoBroadcast({ nodeId: this.nodeId, channel, data });
376
+ }
377
+ _subscribeConferenceModerator(channel) {
378
+ return __awaiter(this, void 0, void 0, function* () {
379
+ const _modCommand = (command, memberID = null, value = null) => {
380
+ const id = parseInt(memberID) || null;
381
+ this._confControl(channel, { command, id, value });
382
+ };
383
+ const _videoRequired = () => {
384
+ const { video } = this.options;
385
+ if ((typeof video === 'boolean' && !video) || (typeof video === 'object' && objEmpty(video))) {
386
+ throw `Conference ${this.id} has no video!`;
387
+ }
388
+ };
389
+ const tmp = {
390
+ nodeId: this.nodeId,
391
+ channels: [channel],
392
+ handler: (params) => {
393
+ const { data } = params;
394
+ switch (data['conf-command']) {
395
+ case 'list-videoLayouts':
396
+ if (data.responseData) {
397
+ const tmp = JSON.stringify(data.responseData).replace(/IDS"/g, 'Ids"');
398
+ this._dispatchConferenceUpdate({ action: ConferenceAction.LayoutList, layouts: JSON.parse(tmp) });
399
+ }
400
+ break;
401
+ default:
402
+ this._dispatchConferenceUpdate({ action: ConferenceAction.ModCmdResponse, command: data['conf-command'], response: data.response });
403
+ }
404
+ }
405
+ };
406
+ const response = yield this.session.vertoSubscribe(tmp)
407
+ .catch(error => {
408
+ logger.error('ConfMod subscription error:', error);
409
+ });
410
+ if (checkSubscribeResponse(response, channel)) {
411
+ this.role = Role.Moderator;
412
+ this._addChannel(channel);
413
+ Object.defineProperties(this, {
414
+ listVideoLayouts: {
415
+ configurable: true,
416
+ value: () => {
417
+ _modCommand('list-videoLayouts');
418
+ }
419
+ },
420
+ playMedia: {
421
+ configurable: true,
422
+ value: (file) => {
423
+ _modCommand('play', null, file);
424
+ }
425
+ },
426
+ stopMedia: {
427
+ configurable: true,
428
+ value: () => {
429
+ _modCommand('stop', null, 'all');
430
+ }
431
+ },
432
+ deaf: {
433
+ configurable: true,
434
+ value: (memberID) => {
435
+ _modCommand('deaf', memberID);
436
+ }
437
+ },
438
+ undeaf: {
439
+ configurable: true,
440
+ value: (memberID) => {
441
+ _modCommand('undeaf', memberID);
442
+ }
443
+ },
444
+ startRecord: {
445
+ configurable: true,
446
+ value: (file) => {
447
+ _modCommand('recording', null, ['start', file]);
448
+ }
449
+ },
450
+ stopRecord: {
451
+ configurable: true,
452
+ value: () => {
453
+ _modCommand('recording', null, ['stop', 'all']);
454
+ }
455
+ },
456
+ snapshot: {
457
+ configurable: true,
458
+ value: (file) => {
459
+ _videoRequired();
460
+ _modCommand('vid-write-png', null, file);
461
+ }
462
+ },
463
+ setVideoLayout: {
464
+ configurable: true,
465
+ value: (layout, canvasID) => {
466
+ _videoRequired();
467
+ const value = canvasID ? [layout, canvasID] : layout;
468
+ _modCommand('vid-layout', null, value);
469
+ }
470
+ },
471
+ kick: {
472
+ configurable: true,
473
+ value: (memberID) => {
474
+ _modCommand('kick', memberID);
475
+ }
476
+ },
477
+ muteMic: {
478
+ configurable: true,
479
+ value: (memberID) => {
480
+ _modCommand('tmute', memberID);
481
+ }
482
+ },
483
+ muteVideo: {
484
+ configurable: true,
485
+ value: (memberID) => {
486
+ _videoRequired();
487
+ _modCommand('tvmute', memberID);
488
+ }
489
+ },
490
+ presenter: {
491
+ configurable: true,
492
+ value: (memberID) => {
493
+ _videoRequired();
494
+ _modCommand('vid-res-id', memberID, 'presenter');
495
+ }
496
+ },
497
+ videoFloor: {
498
+ configurable: true,
499
+ value: (memberID) => {
500
+ _videoRequired();
501
+ _modCommand('vid-floor', memberID, 'force');
502
+ }
503
+ },
504
+ banner: {
505
+ configurable: true,
506
+ value: (memberID, text) => {
507
+ _videoRequired();
508
+ _modCommand('vid-banner', memberID, encodeURI(text));
509
+ }
510
+ },
511
+ volumeDown: {
512
+ configurable: true,
513
+ value: (memberID) => {
514
+ _modCommand('volume_out', memberID, 'down');
515
+ }
516
+ },
517
+ volumeUp: {
518
+ configurable: true,
519
+ value: (memberID) => {
520
+ _modCommand('volume_out', memberID, 'up');
521
+ }
522
+ },
523
+ gainDown: {
524
+ configurable: true,
525
+ value: (memberID) => {
526
+ _modCommand('volume_in', memberID, 'down');
527
+ }
528
+ },
529
+ gainUp: {
530
+ configurable: true,
531
+ value: (memberID) => {
532
+ _modCommand('volume_in', memberID, 'up');
533
+ }
534
+ },
535
+ transfer: {
536
+ configurable: true,
537
+ value: (memberID, exten) => {
538
+ _modCommand('transfer', memberID, exten);
539
+ }
540
+ }
541
+ });
542
+ }
543
+ });
544
+ }
545
+ _handleChangeHoldStateSuccess(response) {
546
+ response.holdState === 'active' ? this.setState(State.Active) : this.setState(State.Held);
547
+ return true;
548
+ }
549
+ _handleChangeHoldStateError(error) {
550
+ logger.error(`Failed to ${error.action} on call ${this.id}`);
551
+ return false;
552
+ }
553
+ _onRemoteSdp(remoteSdp) {
554
+ let sdp = sdpMediaOrderHack(remoteSdp, this.peer.instance.localDescription.sdp);
555
+ if (this.options.useStereo) {
556
+ sdp = sdpStereoHack(sdp);
557
+ }
558
+ const sessionDescr = sdpToJsonHack({ sdp, type: PeerType.Answer });
559
+ this.peer.instance.setRemoteDescription(sessionDescr)
560
+ .then(() => {
561
+ if (this.gotEarly) {
562
+ this.setState(State.Early);
563
+ }
564
+ if (this.gotAnswer) {
565
+ this.setState(State.Active);
566
+ }
567
+ })
568
+ .catch(error => {
569
+ logger.error('Call setRemoteDescription Error: ', error);
570
+ this.hangup();
571
+ });
572
+ }
573
+ _requestAnotherLocalDescription() {
574
+ if (isFunction(this.peer.onSdpReadyTwice)) {
575
+ trigger(SwEvent.Error, new Error('SDP without candidates for the second time!'), this.session.uuid);
576
+ return;
577
+ }
578
+ Object.defineProperty(this.peer, 'onSdpReadyTwice', { value: this._onIceSdp.bind(this) });
579
+ this._iceDone = false;
580
+ this.peer.startNegotiation();
581
+ }
582
+ _onIceSdp(data) {
583
+ if (this._iceTimeout) {
584
+ clearTimeout(this._iceTimeout);
585
+ }
586
+ this._iceTimeout = null;
587
+ this._iceDone = true;
588
+ const { sdp, type } = data;
589
+ if (sdp.indexOf('candidate') === -1) {
590
+ this._requestAnotherLocalDescription();
591
+ return;
592
+ }
593
+ let msg = null;
594
+ const tmpParams = { sessid: this.session.sessionid, sdp, dialogParams: this.options };
595
+ switch (type) {
596
+ case PeerType.Offer:
597
+ this.setState(State.Requesting);
598
+ msg = new Invite(tmpParams);
599
+ break;
600
+ case PeerType.Answer:
601
+ this.setState(State.Answering);
602
+ msg = this.options.attach === true ? new Attach(tmpParams) : new Answer(tmpParams);
603
+ break;
604
+ default:
605
+ logger.error(`${this.id} - Unknown local SDP type:`, data);
606
+ return this.hangup({}, false);
607
+ }
608
+ this._execute(msg)
609
+ .then(response => {
610
+ const { node_id = null } = response;
611
+ this._targetNodeId = node_id;
612
+ type === PeerType.Offer ? this.setState(State.Trying) : this.setState(State.Active);
613
+ })
614
+ .catch(error => {
615
+ logger.error(`${this.id} - Sending ${type} error:`, error);
616
+ this.hangup();
617
+ });
618
+ }
619
+ _registerPeerEvents() {
620
+ const { instance } = this.peer;
621
+ this._iceDone = false;
622
+ instance.onicecandidate = event => {
623
+ if (this._iceDone) {
624
+ return;
625
+ }
626
+ if (this._iceTimeout === null) {
627
+ this._iceTimeout = setTimeout(() => this._onIceSdp(instance.localDescription), 1000);
628
+ }
629
+ if (event.candidate) {
630
+ logger.info('IceCandidate:', event.candidate);
631
+ }
632
+ else {
633
+ this._onIceSdp(instance.localDescription);
634
+ }
635
+ };
636
+ instance.addEventListener('track', (event) => {
637
+ this.options.remoteStream = event.streams[0];
638
+ const { remoteElement, remoteStream, screenShare } = this.options;
639
+ if (screenShare === false) {
640
+ attachMediaStream(remoteElement, remoteStream);
641
+ }
642
+ });
643
+ instance.addEventListener('addstream', (event) => {
644
+ this.options.remoteStream = event.stream;
645
+ });
646
+ }
647
+ _onMediaError(error) {
648
+ this._dispatchNotification({ type: NOTIFICATION_TYPE.userMediaError, error });
649
+ this.hangup({}, false);
650
+ }
651
+ _dispatchConferenceUpdate(params) {
652
+ this._dispatchNotification(Object.assign({ type: NOTIFICATION_TYPE.conferenceUpdate, call: this }, params));
653
+ }
654
+ _dispatchNotification(notification) {
655
+ if (this.options.screenShare === true) {
656
+ return;
657
+ }
658
+ if (!trigger(SwEvent.Notification, notification, this.id, false)) {
659
+ trigger(SwEvent.Notification, notification, this.session.uuid);
660
+ }
661
+ }
662
+ _execute(msg) {
663
+ if (this.nodeId) {
664
+ msg.targetNodeId = this.nodeId;
665
+ }
666
+ return this.session.execute(msg);
667
+ }
668
+ _init() {
669
+ const { id, userVariables, remoteCallerNumber, onNotification } = this.options;
670
+ if (!id) {
671
+ this.options.id = uuidv4();
672
+ }
673
+ this.id = this.options.id;
674
+ if (!userVariables || objEmpty(userVariables)) {
675
+ this.options.userVariables = this.session.options.userVariables || {};
676
+ }
677
+ if (!remoteCallerNumber) {
678
+ this.options.remoteCallerNumber = this.options.destinationNumber;
679
+ }
680
+ this.session.calls[this.id] = this;
681
+ register(SwEvent.MediaError, this._onMediaError, this.id);
682
+ if (isFunction(onNotification)) {
683
+ register(SwEvent.Notification, onNotification.bind(this), this.id);
684
+ }
685
+ this.setState(State.New);
686
+ logger.info('New Call with Options:', this.options);
687
+ }
688
+ _finalize() {
689
+ const { remoteStream, localStream, remoteElement, localElement } = this.options;
690
+ stopStream(remoteStream);
691
+ stopStream(localStream);
692
+ if (this.options.screenShare !== true) {
693
+ detachMediaStream(remoteElement);
694
+ detachMediaStream(localElement);
695
+ }
696
+ deRegister(SwEvent.MediaError, null, this.id);
697
+ this.peer = null;
698
+ this.session.calls[this.id] = null;
699
+ delete this.session.calls[this.id];
700
+ }
701
+ }