-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
662 lines (581 loc) · 23 KB
/
app.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
let ROLE = null; // Possible values: 'master', 'viewer', null
const LOG_LEVELS = ['debug', 'info', 'warn', 'error'];
let LOG_LEVEL = 'info'; // Possible values: any value of LOG_LEVELS
let viewers = {};
function configureLogging() {
function log(level, messages) {
const text = messages
.map(message => {
if (message instanceof Error) {
const { stack, ...rest } = message;
if (Object.keys(rest).length === 0) {
if (stack) {
return stack;
} else {
return message;
}
}
return `${JSON.stringify(rest, null, 2)}\n${stack}`;
} else if (typeof message === 'object') {
return JSON.stringify(message, null, 2);
} else if (message === undefined) {
return 'undefined';
} else {
return message;
}
})
.join(' ');
const logLine = $(`<div class="${level.toLowerCase()}">`).text(`[${new Date().toISOString()}] [${level}] ${text}\n`);
if (LOG_LEVELS.indexOf(LOG_LEVEL) > LOG_LEVELS.indexOf(level.toLowerCase())) {
logLine.addClass('d-none');
}
$('#logs').append(logLine);
const logsContainer = document.getElementById('logs');
logsContainer.scrollTo(0, logsContainer.scrollHeight);
}
console._error = console.error;
console.error = function(...rest) {
log('ERROR', Array.prototype.slice.call(rest));
console._error.apply(this, rest);
};
console._warn = console.warn;
console.warn = function(...rest) {
log('WARN', Array.prototype.slice.call(rest));
console._warn.apply(this, rest);
};
console._log = console.log;
console.log = function(...rest) {
log('INFO', Array.prototype.slice.call(rest));
console._log.apply(this, rest);
};
console._debug = console.debug;
console.debug = function(...rest) {
log('DEBUG', Array.prototype.slice.call(rest));
console._debug.apply(this, rest);
};
}
function getRandomClientId() {
return Math.random()
.toString(36)
.substring(2)
.toUpperCase();
}
function getFormValues() {
return {
region: $('#region').val(),
channelName: $('#channelName').val(),
channelPattern: $('#channelPattern').val(),
extraChannels: $('#extraChannels').val(),
clientId: $('#clientId').val() || getRandomClientId(),
sendVideo: $('#sendVideo').is(':checked'),
sendAudio: $('#sendAudio').is(':checked'),
streamName: $('#streamName').val(),
ingestMedia: $('#ingest-media').is(':checked'),
showJSSButton: $('#show-join-storage-session-button').is(':checked'),
openDataChannel: $('#openDataChannel').is(':checked'),
widescreen: $('#widescreen').is(':checked'),
fullscreen: $('#fullscreen').is(':checked'),
useTrickleICE: $('#useTrickleICE').is(':checked'),
natTraversalDisabled: $('#natTraversalDisabled').is(':checked'),
forceSTUN: $('#forceSTUN').is(':checked'),
forceTURN: $('#forceTURN').is(':checked'),
accessKeyId: $('#accessKeyId').val(),
endpoint: $('#endpoint').val() || null,
secretAccessKey: $('#secretAccessKey').val(),
sessionToken: $('#sessionToken').val() || null,
enableDQPmetrics: $('#enableDQPmetrics').is(':checked'),
sendHostCandidates: $('#send-host').is(':checked'),
acceptHostCandidates: $('#accept-host').is(':checked'),
sendRelayCandidates: $('#send-relay').is(':checked'),
acceptRelayCandidates: $('#accept-relay').is(':checked'),
sendSrflxCandidates: $('#send-srflx').is(':checked'),
acceptSrflxCandidates: $('#accept-srflx').is(':checked'),
sendPrflxCandidates: $('#send-prflx').is(':checked'),
acceptPrflxCandidates: $('#accept-prflx').is(':checked'),
sendTcpCandidates: $('#send-tcp').is(':checked'),
acceptTcpCandidates: $('#accept-tcp').is(':checked'),
sendUdpCandidates: $('#send-udp').is(':checked'),
acceptUdpCandidates: $('#accept-udp').is(':checked'),
};
}
function toggleDataChannelElements() {
if (getFormValues().openDataChannel) {
$('.datachannel').removeClass('d-none');
} else {
$('.datachannel').addClass('d-none');
}
}
function onStatsReport(report) {
// Only print these to the console, as this prints a LOT of stuff.
console._debug('[STATS]', Object.fromEntries([...report.entries()]));
}
function onStop() {
if (!ROLE) {
return;
}
Object.values(viewers).forEach((element) => {
element[0].stopViewer();
element[1].remove();
});
if (getFormValues().enableDQPmetrics) {
$('#dqpmetrics').addClass('d-none');
$('#webrtc-live-stats').addClass('d-none');
}
$('#form').removeClass('d-none');
$('#stop-viewer-button').addClass('d-none');
ROLE = null;
}
window.addEventListener('beforeunload', onStop);
window.addEventListener('error', function(event) {
console.error(event.message);
event.preventDefault();
});
window.addEventListener('unhandledrejection', function(event) {
console.error(event.reason.toString());
event.preventDefault();
});
configureLogging();
function printFormValues(formValues) {
const copyOfForm = Object.assign({}, formValues);
copyOfForm.accessKeyId = copyOfForm.accessKeyId.replace(/./g, '*');
copyOfForm.secretAccessKey = copyOfForm.secretAccessKey.replace(/./g, '*');
copyOfForm.sessionToken = copyOfForm.sessionToken?.replace(/./g, '*');
console.log('[FORM_VALUES] Running the sample with the following options:', copyOfForm);
}
$('#clear-logs').click(() => {
$('#logs').empty();
});
$('#viewer-button').click(async () => {
const form = $('#form');
form.addClass('d-none');
ROLE = 'viewer';
$('#stop-viewer-button').removeClass('d-none');
const formValues = getFormValues();
let mainElement = $('#viewer');
let viewersContainer = $('#viewers'); // Container for all viewers
let uniqueChannels = new Set(); // Set to keep track of unique channels
// Function to create a viewer
function createViewer(channelName, x, y) {
let viewerId = `viewer-${x}-${y}`;
let clonedViewer = mainElement.clone().attr('id', viewerId).removeClass('d-none').addClass('col-md-3');
clonedViewer.prepend(`<h7 class="viewer-title">Channel: ${channelName}</h7>`);
clonedViewer.find('.remote-view').attr('id', `remote-view-${x}-${y}`);
clonedViewer.find('.local-message').attr('id', `local-message-${x}-${y}`);
clonedViewer.find('.remote-message').attr('id', `remote-message-${x}-${y}`);
clonedViewer.find('.send-message-button').attr('id', `send-message-${x}-${y}`);
viewersContainer.append(clonedViewer);
setupSendMessageHandler(`#send-message-${x}-${y}`, `#local-message-${x}-${y}`, viewerId);
let remoteView = clonedViewer.find('.remote-view')[0];
let localView = null;
let viewerFormValues = { ...formValues, channelName: channelName, clientId: getRandomClientId() };
viewers[viewerId] = [new Viewer(localView, remoteView, viewerFormValues, onStatsReport, event => {
clonedViewer.find('.remote-message').append(`${event.data}\n`);
}), clonedViewer];
viewers[viewerId][0].initialize();
}
// Create viewers for the 4x2 grid
for (let x = 1; x <= 2; x++) {
for (let y = 1; y <= 4; y++) {
let channelName = formValues.channelPattern.replace('X', x).replace('Y', y);
if (!uniqueChannels.has(channelName)) {
uniqueChannels.add(channelName);
createViewer(channelName, x, y);
}
}
}
// Process extra channels
let extraChannels = formValues.extraChannels.split(';');
extraChannels.forEach((channel, index) => {
let trimmedChannel = channel.trim();
if (trimmedChannel && !uniqueChannels.has(trimmedChannel)) {
uniqueChannels.add(trimmedChannel);
createViewer(trimmedChannel, 'extra', index);
}
});
});
$('#stop-viewer-button').click(onStop);
$('#create-channel-button').click(async () => {
const formValues = getFormValues();
createSignalingChannel(formValues);
});
function setupSendMessageHandler(sendButtonSelector, localMessageSelector, viewerId) {
$(sendButtonSelector).click(function() {
const message = $(localMessageSelector).val();
if (message) {
if (viewers[viewerId][0].sendViewerMessage(message)) {
$(localMessageSelector).val('');
}
}
});
}
$('#more-logs').click(async () => {
const logElement = $('#logs');
logElement.height(logElement.height() + 50);
});
$('#less-logs').click(async () => {
const logElement = $('#logs');
logElement.height(Math.max(100, logElement.height() - 50));
});
async function logLevelSelected(event) {
LOG_LEVEL = event.target.getAttribute('data-level').toLowerCase();
// Change which button is selected
for (const child of $('#tabs').children()) {
child.setAttribute('class', event.target.id === child.id ? 'btn btn-primary' : 'btn btn-light');
}
// Make the logs hidden and shown based on the selected level
$('#logs > div').each((idx, child) => {
if (LOG_LEVELS.indexOf(LOG_LEVEL) <= LOG_LEVELS.indexOf(child.classList[0])) {
child.classList.remove('d-none');
} else {
child.classList.add('d-none');
}
});
}
// Fetch regions
fetch('https://api.regional-table.region-services.aws.a2z.com/index.jsons')
.then(res => {
if (res.ok) {
return res.json();
}
return Promise.reject(`${res.status}: ${res.statusText}`);
})
.then(data => {
data?.prices
?.filter(serviceData => serviceData?.attributes['aws:serviceName'] === 'Amazon Kinesis Video Streams')
.map(kinesisVideoServiceData => kinesisVideoServiceData?.attributes['aws:region'])
.sort()
.forEach(region => {
$('#regionList').append(
$('<option>', {
value: region,
text: region,
}),
);
});
$('#region').attr('list', 'regionList');
console.log('[FETCH-REGIONS] Successfully fetched regions!');
})
.catch(err => {
console.error('[FETCH-REGIONS] Encountered error fetching regions', err);
});
// Region verification
$('#region').on('focusout', event => {
const region = event.target.value;
let found = false;
let anyRegions = false;
for (const child of $('dataList').children()) {
anyRegions = true;
if (child.value === region) {
found = true;
break;
}
}
if (!anyRegions) {
return;
}
const regionElement = $('#region');
if (found) {
regionElement.addClass('is-valid');
regionElement.removeClass('is-invalid');
} else {
if (!region) {
$('#region-invalid-feedback').text('Please enter a region!');
} else {
// The dataset used mentions that it does not guarantee accuracy. In the case that
// it does not contain a certain region needed, we can still input regions needed.
$('#region-invalid-feedback').text('This region is not in the list of fetched regions!');
console.warn(`[REGION-VALIDATION] The region entered: \"${region}\" may be invalid!`);
}
regionElement.addClass('is-invalid');
regionElement.removeClass('is-valid');
}
});
async function printPeerConnectionStateInfo(event, logPrefix, remoteClientId) {
const rtcPeerConnection = event.target;
console.debug(logPrefix, 'PeerConnection state:', rtcPeerConnection.connectionState);
if (rtcPeerConnection.connectionState === 'connected') {
console.log(logPrefix, 'Connection to peer successful!');
const stats = await rtcPeerConnection.getStats();
if (!stats) return;
rtcPeerConnection.getSenders().map(sender => {
const trackType = sender.track?.kind;
if (sender.transport) {
const iceTransport = sender.transport.iceTransport;
if (iceTransport) {
const logSelectedCandidate = () =>
console.debug(`Chosen candidate pair (${trackType || 'unknown'}):`, iceTransport.getSelectedCandidatePair());
iceTransport.onselectedcandidatepairchange = logSelectedCandidate;
logSelectedCandidate();
}
} else {
console.error('Failed to fetch the candidate pair!');
}
});
} else if (rtcPeerConnection.connectionState === 'failed') {
if (remoteClientId) {
removeViewerTrackFromMaster(remoteClientId);
}
console.error(logPrefix, `Connection to ${remoteClientId || 'peer'} failed!`);
onPeerConnectionFailed();
}
}
// Read/Write all of the fields to/from localStorage so that fields are not lost on refresh.
const urlParams = new URLSearchParams(window.location.search);
const fields = [
{ field: 'channelName', type: 'text' },
{ field: 'channelPattern', type: 'text' },
{ field: 'extraChannels', type: 'text' },
{ field: 'clientId', type: 'text' },
{ field: 'region', type: 'text' },
{ field: 'accessKeyId', type: 'text' },
{ field: 'secretAccessKey', type: 'text' },
{ field: 'sessionToken', type: 'text' },
{ field: 'endpoint', type: 'text' },
{ field: 'sendVideo', type: 'checkbox' },
{ field: 'sendAudio', type: 'checkbox' },
{ field: 'streamName', type: 'text' },
{ field: 'ingest-media', type: 'checkbox' },
{ field: 'show-join-storage-session-button', type: 'checkbox' },
{ field: 'widescreen', type: 'radio', name: 'resolution' },
{ field: 'fullscreen', type: 'radio', name: 'resolution' },
{ field: 'openDataChannel', type: 'checkbox' },
{ field: 'useTrickleICE', type: 'checkbox' },
{ field: 'natTraversalEnabled', type: 'radio', name: 'natTraversal' },
{ field: 'forceSTUN', type: 'radio', name: 'natTraversal' },
{ field: 'forceTURN', type: 'radio', name: 'natTraversal' },
{ field: 'natTraversalDisabled', type: 'radio', name: 'natTraversal' },
{ field: 'enableDQPmetrics', type: 'checkbox' },
{ field: 'send-host', type: 'checkbox' },
{ field: 'accept-host', type: 'checkbox' },
{ field: 'send-relay', type: 'checkbox' },
{ field: 'accept-relay', type: 'checkbox' },
{ field: 'send-srflx', type: 'checkbox' },
{ field: 'accept-srflx', type: 'checkbox' },
{ field: 'send-prflx', type: 'checkbox' },
{ field: 'accept-prflx', type: 'checkbox' },
{ field: 'send-tcp', type: 'checkbox' },
{ field: 'accept-tcp', type: 'checkbox' },
{ field: 'send-udp', type: 'checkbox' },
{ field: 'accept-udp', type: 'checkbox' },
];
fields.forEach(({ field, type, name }) => {
const id = '#' + field;
// Read field from localStorage
try {
const localStorageValue = localStorage.getItem(field);
if (localStorageValue) {
if (type === 'checkbox' || type === 'radio') {
$(id).prop('checked', localStorageValue === 'true');
} else {
$(id).val(localStorageValue);
}
$(id).trigger('change');
}
} catch (e) {
/* Don't use localStorage */
}
// Read field from query string
if (urlParams.has(field)) {
paramValue = urlParams.get(field);
if (type === 'checkbox' || type === 'radio') {
$(id).prop('checked', paramValue === 'true');
} else {
$(id).val(paramValue);
}
}
// Write field to localstorage on change event
$(id).change(function() {
try {
if (type === 'checkbox') {
localStorage.setItem(field, $(id).is(':checked'));
} else if (type === 'radio') {
fields
.filter(fieldItem => fieldItem.name === name)
.forEach(fieldItem => {
localStorage.setItem(fieldItem.field, fieldItem.field === field);
});
} else {
localStorage.setItem(field, $(id).val());
}
} catch (e) {
/* Don't use localStorage */
}
});
});
/**
* Determines whether the ICE Candidate should be added.
* @param formValues Settings used.
* @param candidate {RTCIceCandidate} iceCandidate to check
* @returns true if the candidate should be added to the peerConnection.
*/
function shouldAcceptCandidate(formValues, candidate) {
const { transport, type } = extractTransportAndType(candidate);
if (!formValues.acceptUdpCandidates && transport === 'udp') {
return false;
}
if (!formValues.acceptTcpCandidates && transport === 'tcp') {
return false;
}
switch (type) {
case 'host':
return formValues.acceptHostCandidates;
case 'srflx':
return formValues.acceptSrflxCandidates;
case 'relay':
return formValues.acceptRelayCandidates;
case 'prflx':
return formValues.acceptPrflxCandidates;
default:
console.warn('ShouldAcceptICECandidate: Unknown candidate type:', candidate.type);
return false;
}
}
$('#natTraversalEnabled').on('click', () => {
$('#accept-host').prop('checked', true);
$('#send-host').prop('checked', true);
$('#accept-relay').prop('checked', true);
$('#send-relay').prop('checked', true);
$('#accept-srflx').prop('checked', true);
$('#send-srflx').prop('checked', true);
$('#accept-prflx').prop('checked', true);
$('#send-prflx').prop('checked', true);
saveAdvanced();
});
$('#forceSTUN').on('click', () => {
$('#accept-host').prop('checked', false);
$('#send-host').prop('checked', false);
$('#accept-relay').prop('checked', false);
$('#send-relay').prop('checked', false);
$('#accept-srflx').prop('checked', true);
$('#send-srflx').prop('checked', true);
$('#accept-prflx').prop('checked', false);
$('#send-prflx').prop('checked', false);
saveAdvanced();
});
$('#forceTURN').on('click', () => {
$('#accept-host').prop('checked', false);
$('#send-host').prop('checked', false);
$('#accept-relay').prop('checked', true);
$('#send-relay').prop('checked', true);
$('#accept-srflx').prop('checked', false);
$('#send-srflx').prop('checked', false);
$('#accept-prflx').prop('checked', false);
$('#send-prflx').prop('checked', false);
saveAdvanced();
});
$('#natTraversalDisabled').on('click', () => {
$('#accept-host').prop('checked', true);
$('#send-host').prop('checked', true);
$('#accept-relay').prop('checked', true);
$('#send-relay').prop('checked', true);
$('#accept-srflx').prop('checked', true);
$('#send-srflx').prop('checked', true);
$('#accept-prflx').prop('checked', true);
$('#send-prflx').prop('checked', true);
saveAdvanced();
});
function saveAdvanced() {
$('#accept-host').trigger('change');
$('#send-host').trigger('change');
$('#accept-relay').trigger('change');
$('#send-relay').trigger('change');
$('#accept-srflx').trigger('change');
$('#send-srflx').trigger('change');
$('#accept-prflx').trigger('change');
$('#send-prflx').trigger('change');
}
/**
* Determines whether the ICE Candidate should be sent to the peer.
* @param formValues Settings used.
* @param candidate {RTCIceCandidate} iceCandidate to check
* @returns true if the candidate should be sent to the peer.
*/
function shouldSendIceCandidate(formValues, candidate) {
const { transport, type } = extractTransportAndType(candidate);
if (!formValues.sendUdpCandidates && transport === 'udp') {
return false;
}
if (!formValues.sendTcpCandidates && transport === 'tcp') {
return false;
}
switch (type) {
case 'host':
return formValues.sendHostCandidates;
case 'srflx':
return formValues.sendSrflxCandidates;
case 'relay':
return formValues.sendRelayCandidates;
case 'prflx':
return formValues.sendPrflxCandidates;
default:
console.warn('ShouldSendICECandidate: Unknown candidate type:', candidate.type);
return false;
}
}
function randomString() {
return Date.now().toString();
}
function extractTransportAndType(candidate) {
const words = candidate.candidate.split(' ');
if (words.length < 7) {
console.error('Invalid ice candidate!', candidate);
return false;
}
// https://datatracker.ietf.org/doc/html/rfc5245#section-15.1
return { transport: words[2], type: words[7] };
}
$('#copy-logs').on('click', async function() {
const logsResult = [];
$('#logs')
.children()
// Only copy the logs that are visible
.filter((_, element) => !element.getAttribute('class')?.includes('d-none'))
.each(function() {
logsResult.push(this.textContent);
});
navigator.clipboard.writeText(logsResult.join(''));
$('#copy-tooltip').tooltip('show');
$('#copy-logs').removeClass('btn-light');
$('#copy-logs').addClass('btn-success');
await new Promise(r => setTimeout(r, 1000));
$('#copy-tooltip').tooltip('hide');
$('#copy-logs').removeClass('btn-success');
$('#copy-logs').addClass('btn-light');
});
$('#listStorageChannels').on('click', async function() {
const formValues = getFormValues();
listStorageChannels(formValues);
});
$('#update-media-storage-configuration-button').on('click', async function() {
const formValues = getFormValues();
updateMediaStorageConfiguration(formValues);
});
$('#describe-media-storage-configuration-button').on('click', async function() {
const formValues = getFormValues();
describeMediaStorageConfiguration(formValues);
});
$('#create-stream-modal').on('show.bs.modal', function() {
// Set the stream name in the modal to the stream name.
$('#create-stream-modal-stream-input').val($('#streamName').val());
});
$('#create-stream-modal-create-stream-button').on('click', async function() {
await createStream({
...getFormValues(),
streamName: $('#create-stream-modal-stream-input').val(),
retentionInHours: $('#create-stream-modal-retention-input').val(),
});
});
$('#join-storage-session-button').on('click', async function() {
const formValues = getFormValues();
joinStorageSessionManually(formValues);
});
// Enable tooltips
$(document).ready(function() {
$('[data-toggle="tooltip"]').tooltip();
// Except the copy-logs tooltip
$('#copy-tooltip').tooltip({ trigger: 'manual' });
});
// The page is all setup. Hide the loading spinner and show the page content.
$('.loader').addClass('d-none');
$('#main').removeClass('d-none');
console.log('Page loaded');