-
Notifications
You must be signed in to change notification settings - Fork 35
/
session.js
568 lines (525 loc) · 18 KB
/
session.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
const Emitter = require('./emitter');
const Promise = require('q');
const Constants = require('./constants');
const Utils = require('./utils');
/**
* @classdesc Session class to start session with zello server and interact with it using <a href="">zello channel api</a>
* @example
var session = new ZCC.Session({
serverUrl: 'wss://zellowork.io/ws/[yournetworkname]',
username: [username],
password: [password]
channel: [channel],
authToken: [authToken],
maxConnectAttempts: 5,
connectRetryTimeoutMs: 1000,
autoSendAudio: true,
noPersistentPlayer: false
);
**/
class Session extends Emitter {
/**
* @param {object} options session options. Options can also include <code>player</code>, <code>decoder</code>, <code>recorder</code> and <code>encoder</code> overrides
* @return {ZCC.Session} <code>ZCC.Session</code> instance
**/
constructor(options) {
super();
const library = Utils.getLoadedLibrary();
Session.validateInitialOptions(options);
this.options = Object.assign({}, library.Sdk.initOptions, {
maxConnectAttempts: 5,
connectRetryTimeoutMs: 1000,
autoSendAudio: true,
noPersistentPlayer: false
}, options);
this.callbacks = {};
this.wsConnection = null;
this.refreshToken = null;
this.seq = 0;
this.maxConnectAttempts = this.options.maxConnectAttempts;
this.connectAttempts = this.maxConnectAttempts;
this.connectRetryTimeoutMs = this.options.connectRetryTimeoutMs;
this.selfDisconnect = false;
this.incomingMessages = {};
this.activeOutgoingMessage = null;
this.activeOutgoingImage = null;
this.wasOnline = false;
this.reconnectTimeout = null;
this.channelConfigurationError = false;
}
getSeq() {
return ++this.seq;
}
static validateInitialOptions(initialOptions) {
if (
!initialOptions ||
!initialOptions.serverUrl ||
!initialOptions.channel ||
(initialOptions.username && !initialOptions.password) ||
(!initialOptions.authToken && !initialOptions.username)
) {
throw new Error(Constants.ERROR_NOT_ENOUGH_PARAMS);
}
if (!initialOptions.serverUrl.match(/^wss?:\/\//i)) {
throw new Error(Constants.ERROR_INVALID_SERVER_PROTOCOL);
}
}
/**
* Connects to zello server and starts new session
*
* @param {function} [userCallback] callback for connection event
* @return {promise} promise that resolves once session successfully started and rejects on sessions start error
* @example
// promise
session.connect()
.then(function(result) {
console.log('Session started: ', result)
})
.catch(function(err) {
console.trace(err);
});
// callback
session.connect(function(err, result) {
if (err) {
console.trace(err);
return;
}
console.log('session started:', result)
});
***/
connect(userCallback = null) {
return this.connectOrReconnect(userCallback);
}
clearExistingReconnectTimeout() {
if (this.reconnectTimeout) {
clearTimeout(this.reconnectTimeout);
}
}
connectOrReconnect(userCallback = null, isReconnect = false) {
let dfd = Promise.defer();
if (!this.connectAttempts) {
this.emit(
this.channelConfigurationError ? Constants.EVENT_SESSION_DISCONNECT : Constants.EVENT_SESSION_FAIL_CONNECT
);
return dfd.reject('Failed to connect');
}
if (this.connectAttempts === this.maxConnectAttempts) {
/**
* The Session has opened a websocket connection to the server and ready to sign in
* @event Session#session_start_connect
*/
this.emit(Constants.EVENT_SESSION_START_CONNECT);
}
this.connectAttempts--;
this.doConnect()
.then(() => {
return this.doLogon();
})
.then((result) => {
if (typeof userCallback === 'function') {
userCallback.apply(this, [null, result]);
}
/**
* The Session has connected and signed in successfully
* @event Session#session_connect
*/
this.emit(Constants.EVENT_SESSION_CONNECT);
dfd.resolve(result);
})
.catch((err) => {
if (this.connectAttempts) {
this.clearExistingReconnectTimeout();
this.reconnectTimeout = setTimeout(() => {
this.connectOrReconnect(userCallback, isReconnect);
}, this.connectRetryTimeoutMs);
return;
}
if (typeof userCallback === 'function') {
userCallback.apply(this, [err]);
}
/**
* The Session has failed to connect or sign in.
* @event Session#session_fail_connect
* @param {string} error Error description
*/
/**
* The Session was disconnected and failed to reconnect
* @event Session#session_disconnect
* @param {string} error Error description
*/
this.emit(isReconnect ? Constants.EVENT_SESSION_DISCONNECT : Constants.EVENT_SESSION_FAIL_CONNECT, err);
});
return dfd.promise;
}
doConnect() {
let dfd = Promise.defer();
this.wsConnection = new WebSocket(this.options.serverUrl);
this.wsConnection.binaryType = 'arraybuffer';
this.wsConnection.addEventListener('open', () => {
return dfd.resolve();
});
this.wsConnection.addEventListener('message', (event) => {
this.wsMessageHandler(event.data);
});
this.wsConnection.addEventListener('error', (err) => {
return dfd.reject(err);
});
this.wsConnection.addEventListener('close', (closeEvent) => {
if (this.selfDisconnect) {
this.selfDisconnect = false;
return;
}
// disconnected from server after initial successful connection
if (dfd.promise.inspect().state === 'fulfilled') {
/**
* The Session was disconnected and will try to reconnect
* @event Session#session_connection_lost
* @param {string} error Error description
*/
this.emit(Constants.EVENT_SESSION_CONNECTION_LOST, closeEvent.reason);
this.clearExistingReconnectTimeout();
this.reconnectTimeout = setTimeout(() => {
this.connectOrReconnect(null, true);
}, this.connectRetryTimeoutMs);
}
});
return dfd.promise;
}
doLogon(refreshToken = '') {
let dfd = Promise.defer();
let params = {
'command': 'logon',
'seq': this.getSeq(),
'channel': this.options.channel
};
if (refreshToken) {
params.refresh_token = refreshToken;
} else {
params.auth_token = this.options.authToken;
}
if (this.options.listenOnly) {
params.listen_only = true;
}
if (this.options.username) {
params.username = this.options.username;
params.password = this.options.password;
}
let callback = (err, data) => {
if (err) {
dfd.reject(err);
return;
}
dfd.resolve(data);
};
this.sendCommand(params, callback);
return dfd.promise;
}
/**
* Closes session and disconnects from zello server. To start session again you need to call <code>session.connect</code>
*/
disconnect() {
this.selfDisconnect = true;
this.wsConnection.close();
}
wsBinaryDataHandler(data) {
let parsedData = Utils.parseIncomingBinaryMessage(data);
switch (parsedData.messageType) {
case Constants.MESSAGE_TYPE_AUDIO:
/**
* The Session is receiving incoming voice message packet (with encoded audio)
* @event Session#incoming_voice_data
* @param {Object} incomingVoicePacket voice message packet object
* @property {Uint8Array} messageData encoded (opus) data
* @property {Number} messageId incoming message id
* @property {Number} packetId incoming packet id
*/
this.emit(Constants.EVENT_INCOMING_VOICE_DATA, parsedData);
break;
case Constants.MESSAGE_TYPE_IMAGE:
this.emit(Constants.EVENT_INCOMING_IMAGE_DATA, parsedData);
break;
}
}
jsonDataHandler(jsonData) {
if (jsonData && jsonData.seq) {
this.handleCallbacks(jsonData);
}
if (jsonData.refresh_token) {
this.refreshToken = jsonData.refresh_token;
}
const library = Utils.getLoadedLibrary();
switch (jsonData.command) {
case 'on_error':
let error = Constants.ERROR_TYPE_UNKNOWN_SERVER_ERROR;
if (jsonData.error) {
error = jsonData.error;
}
/**
* The Session received error message from server
* @event Session#error
* @param {string} error Error description
*/
this.emit(Constants.EVENT_ERROR, error);
break;
case 'on_channel_status':
/**
* The Session is receiving channel status update
* @event Session#status
* @param {JSON} status JSON object
* @property {String} channel channel name
* @property {String} status new channel status
* @property {Number} users_online number of online users
*/
if (!this.wasOnline) {
switch (jsonData.status) {
case Constants.SN_STATUS_ONLINE:
this.wasOnline = true;
this.connectAttempts = this.maxConnectAttempts;
break;
case Constants.SN_STATUS_OFFLINE:
if (jsonData.error && jsonData.error_type === Constants.ERROR_TYPE_CONFIGURATION) {
this.channelConfigurationError = true;
}
break;
}
}
this.emit(Constants.EVENT_STATUS, jsonData);
break;
case 'on_stream_start':
const incomingMessage = new library.IncomingMessage(jsonData, this);
this.incomingMessages[jsonData.stream_id] = incomingMessage;
/**
* Incoming voice message is about to start.
* @event Session#incoming_voice_will_start
* @param {ZCC.IncomingMessage} incomingMessage message instance
*/
this.emit(Constants.EVENT_INCOMING_VOICE_WILL_START, incomingMessage);
break;
case 'on_stream_stop':
/**
* Incoming voice message stopped
* @event Session#incoming_voice_did_stop
* @param {ZCC.IncomingMessage} incomingMessage incoming message instance
*/
this.emit(Constants.EVENT_INCOMING_VOICE_DID_STOP, this.incomingMessages[jsonData.stream_id]);
break;
case 'on_text_message':
/**
* Incoming channel text message
* @event Session#incoming_text_message
* @param json textMessage textMessage JSON
*/
this.emit(Constants.EVENT_INCOMING_TEXT_MESSAGE, jsonData);
break;
case 'on_location':
/**
* Incoming location coordinates
* @event Session#incoming_location
* @param json location location data JSON
*/
this.emit(Constants.EVENT_INCOMING_LOCATION, jsonData);
break;
case 'on_image':
/**
* Incoming image JSON metadata
* @event Session#incoming_image
* @param {ZCC.IncomingImage} IncomingImage incoming image instance
*/
const incomingImage = new library.IncomingImage(jsonData, this);
this.emit(Constants.EVENT_INCOMING_IMAGE, incomingImage);
break;
case 'on_dispatch_call_status':
/**
* Incoming dispatch call status change information
* @event Session#dispatch_call_status
* @param json dispatch call status JSON object
* @property {string} channel channel name.
* @property {string} status updated status of the call - one of 'taken', 'received', 'ended'.
* @property {number} call_id dispatch call unique identifier.
* @property {string} dispatcher user name of the dispatcher who has taken the call.
* @property {string} dispatcher_display_name display name of the dispatcher who has taken the call.
* @property {string} dispatcher_profile_picture profile picture URL of the dispatcher who has taken the call.
*/
this.emit(Constants.EVENT_DISPATCH_CALL_STATUS, jsonData);
break;
}
}
wsMessageHandler(data) {
let jsonData = null;
try {
jsonData = JSON.parse(data);
} catch (e) { }
if (!jsonData) {
return this.wsBinaryDataHandler(data);
}
return this.jsonDataHandler(jsonData);
}
handleCallbacks(jsonData) {
let error = jsonData.error ? jsonData.error : null;
let callback = this.callbacks[jsonData.seq];
if (typeof callback !== 'function') {
return;
}
callback.apply(this, [error, jsonData]);
delete this.callbacks[jsonData.seq];
}
sendCommand(params, callback = null) {
if (params.seq && callback) {
this.callbacks[params.seq] = callback;
}
this.wsConnection.send(JSON.stringify(params));
}
sendBinary(data) {
this.wsConnection.send(data);
}
startStream(options = {}, userCallback = null) {
return this.sendCommandWithCallback('start_stream', options, userCallback);
}
stopStream(options = {}, userCallback = null) {
return this.sendCommandWithCallback('stop_stream', options, userCallback);
}
/**
* Starts a voice message by creating OutgoingMessage instance
*
* @param {object} options options for outgoing messages.
* Options can also include <code>recorder</code> and <code>encoder</code> overrides.
* @param {function} [userCallback] callback called once the voice message has been started or failed to start.
*
* @return {ZCC.OutgoingMessage} OutgoingMessage object
* @example
*
// use default recorder and encoder
var outgoingMessage = session.startVoiceMessage();
// use custom recorder
var outgoingMessage = session.startVoiceMessage({
recorder: CustomRecorder
});
// use custom recorder and encoder
var outgoingMessage = session.startVoiceMessage({
recorder: CustomRecorder,
encoder: CustomEncoder
});
// specify custom talk priority
// standard values are talkPriorityNormal and talkPriorityLow
var outgoingMessage = session.startVoiceMessage({
talkPriority: ZCC.OutgoingMessage.talkPriorityNormal
});
**/
startVoiceMessage(options = {}, userCallback = null) {
const library = Utils.getLoadedLibrary();
this.activeOutgoingMessage = new library.OutgoingMessage(this, options, userCallback);
this.activeOutgoingMessage.on(Constants.EVENT_DATA_ENCODED, (data) => {
if (!this.activeOutgoingMessage.options.autoSendAudio) {
return;
}
this.sendBinary(data);
});
return this.activeOutgoingMessage;
}
onIncomingVoiceDidStart(incomingMessage) {
/**
* Incoming voice message did start (first packet received)
*
* @event Session#incoming_voice_did_start
* @param {ZCC.IncomingMessage} incoming message instance
*/
this.emit(Constants.EVENT_INCOMING_VOICE_DID_START, incomingMessage);
}
onIncomingVoiceDecoded(pcmData, incomingMessage) {
/**
* Incoming voice message packet decoded
* @event Session#incoming_voice_data_decoded
* @param {Float32Array} pcmData decoded pcm packet
* @param {ZCC.IncomingMessage} incoming message instance
*/
this.emit(Constants.EVENT_INCOMING_VOICE_DATA_DECODED, pcmData, incomingMessage);
}
/**
* Starts sending an image message by creating OutgoingImage instance
*
* @param {object} options options for outgoing image.
* @property {String} for optional username to send this image to
* @property {Boolean} preview set it to false to automatically send an image without previewing.
* if set to true (default) you will need to call OutgoingImage.send() to send an image
* @property {File} File object (optional) if provided this file is send as an image with a source 'library'
*
* @return {ZCC.OutgoingImage} OutgoingImage object
* @example
*
var outgoingImage = session.sendImage({
preview: false,
for: 'username'
});
**/
sendImage(options = {}) {
const library = Utils.getLoadedLibrary();
this.activeOutgoingImage = new library.OutgoingImage(this, options);
return this.activeOutgoingImage;
}
/**
* Sends a text message
*
* @param {object} options options for outgoing text message.
* @property {String} for optional username to send this text message to
* @property {String} text message text
*
* @param {function} [userCallback] callback that is fired on message being send or failed to be sent
* @return {promise} promise that resolves once session successfully send a text message and rejects if
* text message sending failed
* @example
*
session.sendTextMessage({
for: 'username',
text: 'Hello Zello!'
});
**/
sendTextMessage(options = {}, userCallback = null) {
return this.sendCommandWithCallback('send_text_message', options, userCallback);
}
sendLocation(options = {}, userCallback = null) {
return this.sendCommandWithCallback('send_location', options, userCallback)
}
/**
* Stops an ongoing dispatch call
*
* @param {Number} callId the ID of the ongoing dispatch call to be over.
* @param {function} [userCallback] callback that is fired on dispatch call is over or failed to be stopped.
* @return {promise} promise that resolves once session successfully stopped the dispatch call and rejects if
* stopping the dispatch call is failed.
* @example
*
session.endDispatchCall(123456789);
**/
endDispatchCall(callId, userCallback = null) {
const options = {
call_id: callId,
channel: this.options.channel
};
return this.sendCommandWithCallback(
'end_dispatch_call',
options,
userCallback
);
}
sendCommandWithCallback(command, options, userCallback = null) {
options.seq = this.getSeq();
options.command = command;
let dfd = Promise.defer();
let callback = (err, data) => {
if (err) {
if (typeof userCallback === 'function') {
userCallback.apply(this, [err]);
}
dfd.reject(err);
return;
}
if (typeof userCallback === 'function') {
userCallback.apply(this, [null, data]);
}
dfd.resolve(data);
};
this.sendCommand(options, callback);
return dfd.promise;
}
}
module.exports = Session;