forked from apidaze/apidaze-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
CLIENT.js
728 lines (635 loc) · 20 KB
/
CLIENT.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
import Call from "./Call.js";
import Logger from "./Logger.js";
var __VERSION__ = process.env.VERSIONSTR; // webpack defineplugin variable
var STATUS_INIT = 1;
var STATUS_READY = 2;
var LOG_PREFIX = "APIdaze-" + __VERSION__ + " | CLIENT |";
var LOGGER = new Logger(false, LOG_PREFIX);
var CLIENT = function(configuration = {}) {
let {
apiKey,
wsurl,
forcewsurl,
sessid = null,
onReady,
onDisconnected,
onError,
onExternalMessageReceived,
debug,
userKeys = {},
iceServers
} = configuration;
/**
* Functions exposed to user
*/
this.speedTest = speedTest.bind(this);
this.ping = ping.bind(this);
this.shutdown = shutdown.bind(this);
this.freeAll = shutdown.bind(this); // freeAll is kept for compatibility reasons
this.disconnect = shutdown.bind(this); // disconnect is kept for compatibility reasons
this.sendText = sendText.bind(this);
this.getWebsocketServer = getWebsocketServer.bind(this);
// User defined handlers
this._onDisconnected = function() {
typeof onDisconnected === "function" && onDisconnected();
LOGGER.log("Disconnected");
};
this._onReady = function(sessionObj) {
this._status += STATUS_READY;
LOGGER.log("Ready");
typeof onReady === "function" && onReady(sessionObj);
};
this._onError = function(errorObj) {
/**
* We may receive errors from FreeSWITCH over the WebSocket channel, in
* this case, any exception thrown would be un-catchable. Such errors
* are marcked with a type === "async". For more details, see :
* https://stackoverflow.com/questions/16316815/catch-statement-does-not-catch-thrown-error
*/
typeof onError === "function"
? onError(errorObj.message)
: LOGGER.log("Error : " + errorObj.message);
if (errorObj.type !== "async") {
throw { ok: false, message: errorObj.message, origin: errorObj.origin };
}
};
this._onExternalMessageReceived = function(messageObject) {
// messageObject : {from, to, body}
typeof onExternalMessageReceived === "function" &&
onExternalMessageReceived(messageObject);
};
if (debug) {
this.debug = true;
LOGGER._debug = true;
} else {
this.debug = false;
}
if (!apiKey) {
this._onError({ origin: "CLIENT", message: "Please provide an apiKey" });
}
if (!("WebSocket" in window)) {
this._onError({ origin: "CLIENT", message: "WebSocket not supported" });
}
if (/wss:\/\//.test(forcewsurl)) {
wsurl = forcewsurl;
}
// WebSocket URLs must start with wss:// or ws://localhost (the latter
// for testing purpose)
if (!/wss:\/\//.test(wsurl) && !/ws:\/\/localhost/.test(wsurl)) {
this._onError({
origin: "CLIENT",
message: "Wrong WebSocket URL, must start with wss://"
});
}
this._callArray = [];
this._apiKey = apiKey.toString();
this._status = STATUS_INIT;
this._sessid = sessid;
this._userKeys = userKeys;
this._wsUrl = wsurl;
this._iceServers = iceServers;
this._websocket = new WebSocket(wsurl);
this._websocket.onopen = handleWebSocketOpen.bind(this);
this._websocket.onerror = handleWebSocketError.bind(this);
this._websocket.onmessage = handleWebSocketMessage.bind(this);
this._websocket.onclose = handleWebSocketClose.bind(this);
};
CLIENT.prototype.version = __VERSION__;
CLIENT.prototype._sendMessage = function(json) {
if (this._websocket.readyState !== WebSocket.OPEN) {
this._onError({
origin: "CLIENT",
message: "Client is not ready (WebSocket not open)"
});
return;
}
if (
(this._status & STATUS_READY) === 0 &&
JSON.parse(json).method !== "ping"
) {
this._onError({
origin: "CLIENT",
message: "Client is not ready (hello not received from server)"
});
return;
}
LOGGER.log("handleWebSocketMessage | C->S : " + json);
this._websocket.send(json);
};
CLIENT.prototype.call = function(params, listeners = {}) {
try {
var callObj = new Call(this, null, params, listeners);
this._callArray.push(callObj);
return callObj;
} catch (error) {
error.origin = "call";
error.type = "async";
this._onError(error);
}
};
CLIENT.prototype.reattach = function(callID, params = {}, listeners = {}) {
try {
var callObj = new Call(this, callID, params, listeners);
this._callArray.push(callObj);
return callObj;
} catch (error) {
error.origin = "reattach";
error.type = "async";
this._onError(error);
}
};
/**
* Log connection event and update status
*/
const handleWebSocketOpen = function() {
LOGGER.log("handleWebSocketOpen | WebSocket opened");
var request = {};
request.wsp_version = "1";
request.method = "ping";
request.params = {
apiKey: this._apiKey,
sessid: this._sessid,
userKeys: this._userKeys
};
this._sendMessage(JSON.stringify(request));
};
/**
* Call CLIENT.onError() and throw error
*/
const handleWebSocketError = function() {
LOGGER.log("handleWebSocketError | Error ");
this._onError({
type: "async",
origin: "CLIENT",
message: "WebSocket error"
});
};
/**
* Handle messages from mod_verto
*/
const handleWebSocketMessage = function(event) {
LOGGER.log("handleWebSocketMessage | S->C : " + event.data);
// Special sub proto
if (event.data[0] == "#" && event.data[1] == "S" && event.data[2] == "P") {
if (event.data[3] == "U") {
this.up_dur = parseInt(event.data.substring(4));
} else if (event.data[3] == "D") {
this.down_dur = parseInt(event.data.substring(4));
var up_kps = (
(this._speedBytes * 8) /
(this.up_dur / 1000) /
1000
).toFixed(0);
var down_kps = (
(this._speedBytes * 8) /
(this.down_dur / 1000) /
1000
).toFixed(0);
// eslint-disable-next-line no-console
console.info(
"Speed Test: Up: " + up_kps + "kbit/s Down: " + down_kps + "kbits/s"
);
if (typeof this._speedCB === "function") {
this._speedCB({
upDur: this.up_dur,
downDur: this.down_dur,
upKPS: up_kps,
downKPS: down_kps
});
this._speedCB = null;
}
}
return;
}
var json = JSON.parse(event.data);
if (json.error) {
if (json.error.code === -32602) {
LOGGER.log("Not allowed to login");
this._onError({
type: "async",
origin: "CLIENT",
message: "Not allowed to login"
});
return;
}
if (json.error.code === -32002) {
LOGGER.log("Session error");
this._onError({
type: "async",
origin: "CLIENT",
message: json.error.message
});
return;
}
}
// Handle echo reply to our echo request
if (json.result && json.result.type === "echo_request") {
handleEchoReply.call(this, json);
return;
}
// Handle replies from our sendText function
if (json.result && json.result.type === "sendtext_request") {
handleSendTextReply.call(this, json);
return;
}
// Handle response to our initial 'subscribe_message' request
if (/^subscribe_message/.test(json.id)) {
let callID = json.id.split("|")[1];
handleSubscribeFromVerto.call(this, json, callID);
return;
}
// Handle response to our initial 'conference blabla list' request
if (/^conference_list_command/.test(json.id)) {
let callID = json.id.split("|")[1];
handleConferenceListResponse.call(this, json, callID);
return;
}
if (json.result) {
// Process reponse after request from gateway
if (json.result.message) {
let callID = null; // generated by APIdaze
let sessid = null; // gotten back from FreeSWITCH, identifies the WebSocket
let index = -1;
switch (json.result.message) {
case "pong":
// this._status *= STATUS_RECVD_PONG;
return;
case "CALL CREATED":
LOGGER.log("Got CALL CREATED event");
callID = json.result.callID;
sessid = json.result.sessid;
index = this._callArray.findIndex(function(callObj) {
return callObj.callID === callID;
});
if (index < 0) {
LOGGER.log("Cannot find call with callID " + callID);
} else {
LOGGER.log(
"Call created with callID " + callID + " and sessid " + sessid
);
this._callArray[index].sessid = sessid;
this._sessid = sessid;
}
return;
case "CALL ENDED":
LOGGER.log("Got CALL ENDED event");
callID = json.result.callID;
index = this._callArray.findIndex(function(callObj) {
return callObj.callID === callID;
});
if (index < 0) {
LOGGER.log("Cannot find call with callID " + callID);
} else {
LOGGER.log("Call ended with callID " + callID);
}
this._callArray[index]._onHangup();
this._callArray[index] = null;
this._callArray.splice(index, 1);
return;
default:
break;
}
}
if (json.result.action) {
switch (json.result.action) {
case "sendDTMF":
LOGGER.log("DTMF sent");
return;
default:
return;
}
}
}
if (json.method === "event") {
handleVertoEvent.call(this, json);
return;
}
if (json.method === "verto.clientReady") {
this._onReady({ id: json.params.id, sessid: json.params.sessid });
return;
}
if (json.method === "verto.info") {
// Handle unsollicited text messages, received even when we're not in a call
LOGGER.log("Received message from server", JSON.stringify(json.params.msg));
this._onExternalMessageReceived(json.params.msg);
return;
}
let callID = json.params && json.params.callID;
let index = this._callArray.findIndex(function(callObj) {
return callObj.callID === callID;
});
if (callID && index < 0) {
LOGGER.log("Cannot find call with callID " + callID);
}
/**
* FreeSWITCH can send us its SDP from various actions :
* media (early media)
* answer
* ringing (if using <ringtone/> or <ringback/> from the API)
*
* We need to check whenever we get an SDP from FreeSWITCH and
* call setRemoteDescription right way
*/
switch (json.method) {
case "ringing":
LOGGER.log(
"Ringing on call with callID " + this._callArray[index].callID
);
// FS may send SDP along with ringing event
if (json.params.sdp) {
this._callArray[index].setRemoteDescription(json.params.sdp);
}
this._callArray[index]._onRinging();
break;
case "media":
// In this case, we consider the call is ringing
LOGGER.log("Found call index : " + index);
if (json.params.sdp) {
this._callArray[index].setRemoteDescription(json.params.sdp);
}
this._callArray[index]._onRinging();
break;
case "answer":
LOGGER.log("Found call index : " + index);
if (json.params.sdp) {
this._callArray[index].setRemoteDescription(json.params.sdp);
}
this._callArray[index]._onAnswer();
break;
case "hangup":
LOGGER.log("Hangup call with callID " + this._callArray[index].callID);
this._callArray[index]._onHangup();
this._callArray[index] = null;
this._callArray.splice(index, 1);
break;
case "verto.attach":
// We are re-attaching this session to an existing call in FreeSWITCH
LOGGER.log("Re-attaching to call with ID : " + callID);
LOGGER.log("Call index is " + (index < 0) ? "OK" : "Not OK");
this._reattachParams = json.params;
break;
default:
LOGGER.log("No action for this message");
}
};
/**
* Handle events from mod_verto here
*
* The main purpose is to handle conference events, but one may expect to
* get other events here.
*/
const handleVertoEvent = function(event) {
var params = event.params;
LOGGER.log("Received event of type " + params.eventType);
LOGGER.log("Event channel UUID : " + params.eventChannelUUID);
LOGGER.log("Event channel : " + params.eventChannel);
var index = this._callArray.findIndex(function(callObj) {
return callObj.callID === params.eventChannelUUID;
});
if (index >= 0) {
// This is an event generated by one of our sessions (not a conference)
LOGGER.log("Need to handle simple event");
if (params.pvtData.action === "conference-liveArray-join") {
/**
* We receive this message the first time we join the conference.
* Two actions performed :
* - Send a subscribe message to FreeSWITCH in order to get all the
* conference events from this conference
* - Retrieve list of current participants in the room
*/
let request = {};
request.wsp_version = "1";
request.method = "verto.subscribe";
request.id = "subscribe_message|" + this._callArray[index].callID;
request.params = {
eventChannel: [
event.params.pvtData.laChannel,
event.params.pvtData.chatChannel,
event.params.pvtData.infoChannel
],
subParams: {}
};
this._sendMessage(JSON.stringify(request));
request.wsp_version = "1";
request.method = "jsapi";
request.id = "conference_list_command|" + this._callArray[index].callID;
request.params = {
command: "fsapi",
data: {
cmd: "conference",
arg: event.params.pvtData.laName + " list"
}
};
this._sendMessage(JSON.stringify(request));
/**
* Set parameters to our callObj
* - callType to 'conference'
* - conferenceMemberID identifies me in the conference
*/
this._callArray[index].callType = "conference";
this._callArray[index].conferenceMemberID = parseInt(
event.params.pvtData.conferenceMemberID
);
this._callArray[index].conferenceName = event.params.pvtData.laName;
}
return;
}
if (index < 0) {
/**
* Could not find call that matches with eventChannelUUID, try to find
* a match using eventChannel. This occurs in the following cases :
* - a liveArray event indicating who's talking, entering, leaving the room
* has been received
* - a group chat message is the room has been received
*/
index = this._callArray.findIndex(function(callObj) {
return callObj.subscribedChannelsArray.indexOf(params.eventChannel) >= 0;
});
}
if (index >= 0) {
if (/^conference-liveArray/.test(event.params.eventChannel)) {
// eslint-disable-next-line no-console
console.log("event.params.data : ", JSON.stringify(event.params.data));
let data = event.params.data.data;
Array.isArray(data) && data.push(event.params.data.hashKey);
switch (event.params.data.action) {
case "modify":
// Who is talking events are received here
this._callArray[index]._onRoomTalking(data);
break;
case "add":
// Some joined the conference
this._callArray[index]._onRoomAdd(data);
break;
case "del":
// Someone left the conference
this._callArray[index]._onRoomDel(data);
break;
}
} else if (/^conference-chat/.test(event.params.eventChannel)) {
// group chat message received
this._callArray[index]._onRoomChatMessage(event.params.data);
}
return;
}
this._onError({
type: "async",
message: "Failed to find call object that matches with conf event",
origin: "conference"
});
};
/**
* Handle response from FreeSWITCH to our initial verto.subscribe request
*/
const handleSubscribeFromVerto = function(event, callID) {
var index = this._callArray.findIndex(function(callObj) {
return callObj.callID === callID;
});
if (index < 0) {
LOGGER.log(
"Cannot find a call object that matches with sessid " + event.sessid
);
throw { ok: false, message: "Failed to process reply to subscribe" };
}
/**
* I hope FreeSWITCH dumps the channels in the same order :
* - laChannel : LiveArray, all events from the conference
* - chatChannel : chat messages
* - infoChannel : info ?
*/
this._callArray[index].subscribedChannels = {};
let channelsArray = [];
if (event.result.subscribedChannels.length === 3) {
LOGGER.log("Found valid subscribedChannels[] array");
channelsArray = event.result.subscribedChannels;
} else if (event.result.alreadySubscribedChannels.length === 3) {
LOGGER.log("Found valid alreadySubscribedChannels[] array");
channelsArray = event.result.alreadySubscribedChannels;
}
this._callArray[index].subscribedChannels.laChannel = channelsArray[0];
this._callArray[index].subscribedChannels.chatChannel = channelsArray[1];
this._callArray[index].subscribedChannels.infoChannel = channelsArray[2];
this._callArray[index].subscribedChannelsArray = channelsArray;
};
/**
* Handle response from FreeSWITCH to our 'conference_list_command'
*
* We just get the list of the participants in the conference room we're joining.
*/
const handleConferenceListResponse = function(event, callID) {
var index = this._callArray.findIndex(function(callObj) {
return callObj.callID === callID;
});
if (index < 0) {
LOGGER.log(
"Cannot find a call object that matches with sessid " + event.sessid
);
throw {
ok: false,
message: "Failed to process reply to conference_list_command"
};
}
LOGGER.log("Got members " + JSON.stringify(event));
var members = [];
var lines = event.result.message.split("\n");
for (var idx = 0; idx < lines.length - 1; idx++) {
var elems = lines[idx].split(";");
members.push({
sessid: elems[2],
nickname: elems[3],
caller_id_number: elems[4],
conferenceMemberID: elems[0],
talking_flags: elems[5]
});
}
this._callArray[index]._onRoomMembersInitialList(members);
};
/**
* Log connection event, update status, call CLIENT.onDisconnected()
*/
const handleWebSocketClose = function() {
LOGGER.log("handleWebSocketClose | WebSocket closed");
this._status = STATUS_INIT;
this._onDisconnected();
};
const handleEchoReply = function(event) {
var now = Date.now();
var rtt = now - parseInt(event.result.time);
LOGGER.log("handleEchoReply RTT : " + rtt + "ms");
if (typeof this._pingCallback === "function") {
this._pingCallback(rtt);
this._pingCallback = null;
}
};
const handleSendTextReply = function(event) {
LOGGER.log("handleSendTextReply", JSON.stringify(event));
if (typeof this._sendTextCallback === "function") {
this._sendTextCallback({
httpCode: event.result.httpCode || null,
ok: event.result.ok,
message: event.result.message,
data: event.result.data || null
});
this._sendTextCallback = null;
}
};
const shutdown = function() {
if (this._websocket === null) {
return;
}
this._websocket.close();
this._websocket = null;
};
const sendText = function({ text, userKeys = {} }, userCallback) {
this._sendTextCallback = userCallback;
var request = {};
request.wsp_version = "1";
request.method = "verto.info";
request.params = {
type: "sendtext_request",
text: text,
userKeys: typeof userKeys !== "object" ? {} : userKeys
};
this._sendMessage(JSON.stringify(request));
};
const getWebsocketServer = function() {
try {
var matches = this._wsUrl.match(/^wss?:\/\/([^/:?#]+)(?:[/:?#]|$)/i);
var host = matches && matches[1];
return host;
} catch (error) {
return false;
}
};
const speedTest = function(userCallback, bytes = 1024 * 256) {
var socket = this._websocket;
if (socket !== null) {
this._speedCB = userCallback;
this._speedBytes = bytes;
socket.send("#SPU " + bytes);
var loops = bytes / 1024;
var rem = bytes % 1024;
var i;
var data = new Array(1024).join(".");
for (i = 0; i < loops; i++) {
socket.send("#SPB " + data);
}
if (rem) {
socket.send("#SPB " + data);
}
socket.send("#SPE");
}
};
const ping = function(userCallback) {
var now = Date.now();
var request = {};
this._pingCallback = userCallback;
request.wsp_version = "1";
request.method = "echo";
request.params = {
type: "echo_request",
time: now
};
this._sendMessage(JSON.stringify(request));
};
export default CLIENT;