@telegenta/webclient 3.4.0 → 3.4.1

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.
@@ -0,0 +1,590 @@
1
+ <!DOCTYPE html>
2
+ <html lang="en">
3
+ <meta name="keywords" content="telegenta, phone client, webrtc, demo" />
4
+ <meta name="description" content="Telegenta Phone client demo application using telegenta client library" />
5
+
6
+ <head>
7
+ <meta charset="UTF-8" />
8
+ <title>Telegenta Phone client Demo</title>
9
+ <script src="../dist/telegenta.min.js"></script>
10
+ <link rel="stylesheet" type="text/css" href="styles.css" />
11
+ </head>
12
+
13
+ <body>
14
+ <!-- Logo -->
15
+ <div class="groupelementsnoline" id="Telegenta"></div>
16
+ <!-- Logo end -->
17
+ <div>
18
+ <div class="groupelementsnoline">
19
+ <h2>Telegenta Phone Client Demo</h2>
20
+ </div>
21
+ <div class="groupelements">
22
+ <h3>STEP 1: Get account list</h3>
23
+ <div class="inputelements">
24
+ <label for="api_key">API Key</label>
25
+ <input type="text" size="40" id="api_key" placeholder="Enter API Key" value="" />
26
+ <button onclick="populateSelectElements()">Get sip accounts</button>
27
+ </div>
28
+ </div>
29
+
30
+ <div class="groupelements">
31
+ <h3>STEP 2: Start phone</h3>
32
+ <div class="inputelements">
33
+ <label for="account_selector">SIP Accounts</label
34
+ ><span class="smallright"
35
+ ><small>Connection: <span id="conn_status">DISCONNECTED</span></small></span
36
+ >
37
+ <select id="account_selector">
38
+ <option value="" disabled selected>Waiting for SIP accounts</option>
39
+ </select>
40
+ <button onclick="startPhoneClient()">Start phone and use selected account</button>
41
+ <button onclick="stopPhoneClient()">Stop the phone client</button>
42
+ </div>
43
+ </div>
44
+
45
+ <div class="groupelements">
46
+ <h3>STEP 3: Add a new call</h3>
47
+ <div class="inputelements">
48
+ <label for="destination_number">Number to call</label
49
+ ><span class="smallright"
50
+ ><small
51
+ >Status: <span id="call_status">IDLE</span> &nbsp;| Duration:
52
+ <span id="call_duration">-</span></small
53
+ ></span
54
+ >
55
+ <input type="text" size="40" id="destination_number" placeholder="Enter phone number" value="" />
56
+ <button onclick="makeCall()">Call number now</button>
57
+ </div>
58
+ </div>
59
+
60
+ <div class="groupelements">
61
+ <h3>Transfer call</h3>
62
+
63
+ <div class="inputelements">
64
+ <h3 id="transfer_from"></h3>
65
+ <label for="transfer_selector">Select call: </label>
66
+ <select id="transfer_selector">
67
+ <option value="" disabled selected>No call to transfer</option>
68
+ </select>
69
+
70
+ <button onclick="doCallTransfer()">Transfer call</button>
71
+ </div>
72
+ </div>
73
+
74
+ <div class="groupelements">
75
+ <h3>Listen call</h3>
76
+
77
+ <div class="inputelements">
78
+ <h3>Listen to another call</h3>
79
+ <label for="listen_key">Call listen key</label>
80
+ <input type="text" size="40" id="listen_key" placeholder="Enter call listen key" value="" />
81
+ <button onclick="doListen()">Listen now</button>
82
+ </div>
83
+ </div>
84
+
85
+ <div class="groupelements">
86
+ <h3>Playback</h3>
87
+ <div class="inputelements">
88
+ <label for="media_file_selector">Media files</label>
89
+ <select id="media_file_selector">
90
+ <option value="" disabled selected>Select media file</option>
91
+ </select>
92
+ </div>
93
+ </div>
94
+
95
+ <div class="groupelementsnoline">
96
+ <h3>Active calls</h3>
97
+ <table id="session_table">
98
+ <tr>
99
+ <th>Direction</th>
100
+ <th>Destination number</th>
101
+ <th>State</th>
102
+ <th>Duration</th>
103
+ <th>Quality metrics</th>
104
+ <th>Mic muted</th>
105
+ <th>Recording</th>
106
+ <th>On hold</th>
107
+ <th>Actions</th>
108
+ </tr>
109
+ </table>
110
+ </div>
111
+ <div class="groupelementsnoline">
112
+ <small>Tip: Press F12 (developer console) to get additional information</small>
113
+ </div>
114
+ </div>
115
+ </body>
116
+
117
+ <!-- Javascript stuff -->
118
+ <script>
119
+ // The demo is published with the docs on both www.telegenta.com and www.telegenta-test.com
120
+ const API_URL = location.hostname.endsWith('telegenta-test.com')
121
+ ? 'https://api.telegenta-test.com/api'
122
+ : 'https://api.telegenta.com/api';
123
+ let phoneClient = null;
124
+ let logger;
125
+ let transferSession;
126
+
127
+ // Start when DOM is ready
128
+ window.onload = function () {
129
+ // Create phone instance first
130
+ logger = new Telegenta.LogHandler(Telegenta.LOGLVL.DEBUG);
131
+ phoneClient = new Telegenta.Phone(logger);
132
+
133
+ // Check browser is supported first
134
+ if (!phoneClient.browserSupported) {
135
+ console.error('Your browser is not supported');
136
+ } else {
137
+ console.info('Your browser is supported');
138
+ }
139
+ };
140
+
141
+ /*
142
+ * STEP 1: Get a list of sip accounts from API server and populate select box with these accounts
143
+ */
144
+ function populateSelectElements() {
145
+ // SIP Accounts
146
+ jsonApiGetRequest('/sip-trunks/').then(
147
+ function (data) {
148
+ console.info(`Fetched ${data.results.length} sip accounts:`);
149
+ console.debug(data);
150
+
151
+ // Now reset and populate select box with accounts
152
+ document.getElementById('account_selector').innerHTML = '';
153
+ for (const account of data.results) {
154
+ document.getElementById('account_selector').appendChild(new Option(account.name, account.id));
155
+ }
156
+ },
157
+ function (reason) {
158
+ console.error(`Request failed ${reason}`);
159
+ },
160
+ );
161
+
162
+ // Media files
163
+ jsonApiGetRequest('/media-files/').then(
164
+ function (data) {
165
+ console.info(`Fetched ${data.results.length} media files:`);
166
+ console.debug(data);
167
+
168
+ // Now reset and populate select box with accounts
169
+ document.getElementById('media_file_selector').innerHTML = '';
170
+ for (const mfile of data.results) {
171
+ document.getElementById('media_file_selector').appendChild(new Option(mfile.name, mfile.id));
172
+ }
173
+ },
174
+ function (reason) {
175
+ console.error(`Request failed ${reason}`);
176
+ },
177
+ );
178
+ }
179
+
180
+ /*
181
+ * STEP 2: Get a new call_token from API and start phone client with account chosen in select box
182
+ */
183
+ function startPhoneClient() {
184
+ const accountId = document.getElementById('account_selector').value;
185
+ console.info(`Starting phone client with account id ${accountId}`);
186
+
187
+ // Create call session and get provision token
188
+ jsonApiGetRequest(`/get-call-session/?id=${accountId}`).then(
189
+ function (data) {
190
+ console.info('Fetched a new call session');
191
+ console.debug(data);
192
+
193
+ // Now prepare media and get access to microphone
194
+ phoneClient.prepareMedia().then(
195
+ function () {
196
+ // Media was prepared, now hook up events to display whats going on
197
+
198
+ // Connection state shows the client connection to the phone services
199
+ phoneClient.on('connectionStateChange', function (event) {
200
+ console.info(`Phone connection is now: ${event.state}`);
201
+ document.getElementById('conn_status').innerHTML = event.state;
202
+ });
203
+
204
+ // Get local information about call after it has ended
205
+ phoneClient.on('callEnded', function (data) {
206
+ console.info('Call ended event:');
207
+ console.info(data);
208
+ });
209
+
210
+ // Get remote information about call after it has ended
211
+ phoneClient.on('callDataInfo', function (data) {
212
+ console.info('Call data info event:');
213
+ console.info(data);
214
+ });
215
+
216
+ // New session created
217
+ phoneClient.on('sessionCreated', function (data) {
218
+ newSession(data.session);
219
+ });
220
+
221
+ // Session removed
222
+ phoneClient.on('sessionRemoved', function (data) {
223
+ console.log(data);
224
+ removeSession(data.session);
225
+ });
226
+
227
+ // Show incoming call
228
+ phoneClient.on('incomingCall', function (data) {
229
+ console.log(`Incoming call from ${data.originatingNumber}`);
230
+ });
231
+
232
+ // Now start phone with the following options
233
+ const opts = {
234
+ // Enable event client
235
+ connectEventService: true,
236
+
237
+ // Subscribe to detailed information about call after processing
238
+ useCallDataInfoEvent: true,
239
+
240
+ // Enable incoming calls (you must set a phone number to call the account also)
241
+ register: true,
242
+
243
+ // Configure client with provision token
244
+ provisionToken: data.provision_token,
245
+
246
+ // Enable signal tones (busy, invalid, etc)
247
+ playSignalTones: true,
248
+
249
+ // Enable call initialized tone
250
+ playCallInitializedTone: true,
251
+
252
+ // Enable call ended tone
253
+ playCallEndedTone: true,
254
+ };
255
+
256
+ try {
257
+ phoneClient.start(opts);
258
+ console.info('Media prepared and phone started');
259
+ } catch (e) {
260
+ console.error('Unable to start phone');
261
+ console.error(e);
262
+ }
263
+ },
264
+ function (reason) {
265
+ console.error('Unable to get media permission: ' + reason);
266
+ },
267
+ );
268
+ },
269
+ function (reason) {
270
+ console.error(`Request failed ${reason}`);
271
+ },
272
+ );
273
+ }
274
+
275
+ // Stop phone client
276
+ function stopPhoneClient() {
277
+ phoneClient.stop();
278
+ }
279
+
280
+ /*
281
+ * STEP 3: Make a test call
282
+ */
283
+ function makeCall() {
284
+ const destination_number = document.getElementById('destination_number').value;
285
+ phoneClient.call(destination_number, {
286
+ // Change this to number of days to keep recording (enables recording)
287
+ record: 0,
288
+
289
+ // Change this maximum amount in customer currency the call must cost before hanging up (0 = no checking)
290
+ maximumCallCost: 0,
291
+
292
+ // Include this to force a specific caller id (use id of phone number from api service)
293
+ // explicitCallerId: 35,
294
+
295
+ // Include this to force a specific smart cid (use id of shot-cid from api service)
296
+ // explicitShortCallerId: 1,
297
+
298
+ // Configure answer call timeout
299
+ answerCallTimeout: 0,
300
+
301
+ // Add meta info to call
302
+ metaInfo:
303
+ 'You can add up to 256 bytes of meta info for your call (including json like {"type": "json"})',
304
+ });
305
+ }
306
+
307
+ // Set the source of call transfer and populate transfer destination selector
308
+ function setTransferSession(session) {
309
+ transferSession = session;
310
+
311
+ var otherSessions = session.getOtherSessions();
312
+ if (otherSessions.length < 1) {
313
+ document.getElementById('transfer_from').innerHTML =
314
+ 'Requires two active sessions to perform transfer!';
315
+ return;
316
+ }
317
+
318
+ // Show source call destination number
319
+ document.getElementById('transfer_from').innerHTML = session.destinationNumber + ' => ';
320
+
321
+ // Add all other sessions to transfer selector
322
+ document.getElementById('transfer_selector').innerHTML = '';
323
+
324
+ for (const tSession of otherSessions) {
325
+ document
326
+ .getElementById('transfer_selector')
327
+ .appendChild(new Option(tSession.destinationNumber, tSession.uuid));
328
+ }
329
+ }
330
+
331
+ // Transfer call from "transferSession" to item in transfer_selector
332
+ function doCallTransfer() {
333
+ if (!transferSession) {
334
+ console.error('No session selected');
335
+ return;
336
+ }
337
+
338
+ // Use session uuid from selectbox and get session object
339
+ const dstSession = phoneClient.getSessionByUUID(document.getElementById('transfer_selector').value);
340
+
341
+ // Now do transfer
342
+ transferSession.transfer(dstSession);
343
+ }
344
+
345
+ // Create listen session
346
+ function doListen() {
347
+ phoneClient.listen(document.getElementById('listen_key').value);
348
+ }
349
+
350
+ // Playback message
351
+ function playback(session) {
352
+ const hangup_after = false;
353
+ session.playback(document.getElementById('media_file_selector').value, hangup_after).then(() => {
354
+ console.info('Playback started');
355
+ });
356
+ }
357
+
358
+ /*
359
+ * Helper functions
360
+ */
361
+
362
+ // Create new session
363
+ // Add table row for session using session_<uuid> as element id,
364
+ // (We do this so we can find and remove row when session ends)
365
+ function newSession(session) {
366
+ const rowId = `session_${session.uuid}`;
367
+
368
+ // Create row in table for session
369
+ const table = document.getElementById('session_table');
370
+ const newRow = table.insertRow();
371
+ newRow.id = rowId;
372
+ for (let i = 0; i < table.rows[0].cells.length; i++) newRow.insertCell();
373
+
374
+ // Set cells
375
+ newRow.cells[0].innerText = session.direction;
376
+
377
+ // Show name of local number called for inbound
378
+ if (session.localNumberName) {
379
+ newRow.cells[1].innerText = session.destinationNumber + ' (' + session.localNumberName + ')';
380
+ } else {
381
+ newRow.cells[1].innerText = session.destinationNumber;
382
+ }
383
+
384
+ // Hookup events
385
+ // Session state show the current calling state
386
+ session.on('sessionStateChange', function (event) {
387
+ console.info(`Phone session is now: ${event.state}`);
388
+ newRow.cells[2].innerHTML = event.state;
389
+ // Add failure cause
390
+ if (event.state === 'FAILED') {
391
+ newRow.cells[2].innerHTML = newRow.cells[2].innerHTML + ` (${event.cause})`;
392
+ }
393
+ updateButtons(newRow.cells[8], session);
394
+ });
395
+
396
+ // Get record state events
397
+ newRow.cells[6].innerHTML = session.isRecording;
398
+ session.on('recordingStateChange', function (data) {
399
+ console.info(`Recording state changed to ${data.state}`);
400
+ newRow.cells[6].innerHTML = data.state;
401
+ });
402
+
403
+ // Get mute state events
404
+ newRow.cells[5].innerHTML = session.isMuted;
405
+ session.on('muteStateChange', function (data) {
406
+ console.info(`Microphone mute state changed to ${data.state}`);
407
+ newRow.cells[5].innerHTML = data.state;
408
+ });
409
+
410
+ // Get hold state events
411
+ newRow.cells[7].innerHTML = session.isOnHold;
412
+ session.on('holdStateChange', function (data) {
413
+ console.info(`Call hold state changed to ${data.state}`);
414
+ newRow.cells[7].innerHTML = data.state;
415
+ });
416
+
417
+ // Get call duration update events
418
+ session.on('callDurationUpdate', function (data) {
419
+ newRow.cells[3].innerHTML = `${data.durationStr} (${data.activeDurationStr})`;
420
+ });
421
+
422
+ // Get call duration update events
423
+ session.on('callQualityReportUpdate', function (data) {
424
+ console.info('Call quality report:');
425
+ console.info(data);
426
+ newRow.cells[4].innerHTML = `${data.delta.effectiveLatency.toFixed(1)} ms (${data.delta.rFactor.toFixed(
427
+ 1,
428
+ )} R)`;
429
+ });
430
+
431
+ // Get local information about call after it has ended
432
+ session.on('callEnded', function (data) {
433
+ console.info('Call ended event:');
434
+ console.debug(data);
435
+ });
436
+
437
+ session.on('whisperModeChange', function (data) {
438
+ console.info('Whisper mode: ' + data.mode);
439
+ });
440
+ }
441
+
442
+ // Remove table row for session
443
+ function removeSession(session) {
444
+ const row = document.getElementById(`session_${session.uuid}`);
445
+ if (row) {
446
+ row.parentNode.removeChild(row);
447
+ }
448
+ }
449
+
450
+ // Add buttons based on session state on element (the table row)
451
+ function updateButtons(element, session) {
452
+ // Remove all buttons first
453
+ let e = element.firstElementChild;
454
+ while (e) {
455
+ e.remove();
456
+ e = element.firstElementChild;
457
+ }
458
+
459
+ // Put session on TD element, so buttons can use it
460
+ element._session = session;
461
+
462
+ // NON TERMINATED/INCOMING/FAILED BUTTONS
463
+ if (session.state !== 'TERMINATED' && session.state !== 'INCOMING' && session.state !== 'FAILED') {
464
+ const btn = document.createElement('BUTTON');
465
+ btn.innerHTML = 'Hangup';
466
+ btn.onclick = function () {
467
+ this.parentNode._session.hangup();
468
+ };
469
+ element.appendChild(btn);
470
+ }
471
+
472
+ if (session.direction === 'OUTBOUND' || session.direction === 'INBOUND') {
473
+ // ACTIVE CALL BUTTONS
474
+ if (session.state === 'ACTIVE' || session.state === 'ON_HOLD') {
475
+ const btn = document.createElement('BUTTON');
476
+ btn.innerHTML = 'Play tone';
477
+ btn.onclick = function () {
478
+ phoneClient.playTone(1000, 440, 880, function () {
479
+ console.info('Play tone complete!');
480
+ });
481
+ };
482
+ element.appendChild(btn);
483
+
484
+ const btn2 = document.createElement('BUTTON');
485
+ btn2.innerHTML = 'Send DTMF 1';
486
+ btn2.onclick = function () {
487
+ this.parentNode._session.sendDTMF(1);
488
+ };
489
+ element.appendChild(btn2);
490
+
491
+ const btn3 = document.createElement('BUTTON');
492
+ btn3.innerHTML = 'Toggle mute mic';
493
+ btn3.onclick = function () {
494
+ this.parentNode._session.toggleMute();
495
+ };
496
+ element.appendChild(btn3);
497
+
498
+ const btn4 = document.createElement('BUTTON');
499
+ btn4.innerHTML = 'Toggle recording';
500
+ btn4.onclick = function () {
501
+ this.parentNode._session.toggleRecording();
502
+ };
503
+ element.appendChild(btn4);
504
+
505
+ const btn5 = document.createElement('BUTTON');
506
+ btn5.innerHTML = 'Toggle hold';
507
+ btn5.onclick = function () {
508
+ this.parentNode._session.toggleHold();
509
+ };
510
+ element.appendChild(btn5);
511
+
512
+ const btn6 = document.createElement('BUTTON');
513
+ btn6.innerHTML = 'Transfer';
514
+ btn6.onclick = function () {
515
+ setTransferSession(this.parentNode._session);
516
+ };
517
+ element.appendChild(btn6);
518
+
519
+ const btn7 = document.createElement('BUTTON');
520
+ btn7.innerHTML = 'Playback';
521
+ btn7.onclick = function () {
522
+ playback(this.parentNode._session);
523
+ };
524
+ element.appendChild(btn7);
525
+ }
526
+
527
+ // INCOMING BUTTONS
528
+ if (session.state === 'INCOMING') {
529
+ const btn = document.createElement('BUTTON');
530
+ btn.innerHTML = 'Answer';
531
+ btn.onclick = function () {
532
+ this.parentNode._session.answer(
533
+ (metaInfo = 'When answering calls you can add meta info as well'),
534
+ );
535
+ };
536
+ element.appendChild(btn);
537
+
538
+ const btn2 = document.createElement('BUTTON');
539
+ btn2.innerHTML = 'Reject';
540
+ btn2.onclick = function () {
541
+ this.parentNode._session.reject();
542
+ };
543
+ element.appendChild(btn2);
544
+ }
545
+ }
546
+
547
+ // LISTEN BUTTONS
548
+ if (session.direction === 'LISTEN' && session.state === 'ACTIVE') {
549
+ const btn = document.createElement('BUTTON');
550
+ btn.innerHTML = 'Start whisper';
551
+ btn.onclick = function () {
552
+ this.parentNode._session.setWhisperMode(1);
553
+ };
554
+ element.appendChild(btn);
555
+
556
+ const btn2 = document.createElement('BUTTON');
557
+ btn2.innerHTML = 'End whisper';
558
+ btn2.onclick = function () {
559
+ this.parentNode._session.setWhisperMode(0);
560
+ };
561
+ element.appendChild(btn2);
562
+ }
563
+ }
564
+
565
+ // Perform authenticated ajax request to api server and return json payload on success
566
+ function jsonApiGetRequest(path) {
567
+ const xhr = new XMLHttpRequest();
568
+ const url = API_URL + path;
569
+ xhr.open('GET', url, true);
570
+ xhr.responseType = 'json';
571
+ const apiToken = document.getElementById('api_key').value;
572
+ xhr.setRequestHeader('Authorization', 'Bearer ' + apiToken);
573
+ xhr.setRequestHeader('Accept', 'application/json');
574
+
575
+ return new Promise(function (resolve, reject) {
576
+ xhr.onreadystatechange = function () {
577
+ if (xhr.readyState === 4) {
578
+ if (xhr.status !== 200) {
579
+ reject(xhr.status + ' ' + xhr.statusText);
580
+ return;
581
+ }
582
+ resolve(xhr.response);
583
+ }
584
+ };
585
+ console.debug(`API Request: ${url}`);
586
+ xhr.send();
587
+ });
588
+ }
589
+ </script>
590
+ </html>