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