-
Notifications
You must be signed in to change notification settings - Fork 41
/
host.js
781 lines (681 loc) · 25.2 KB
/
host.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
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
/* global analytics http Clipboard */
/* eslint-disable object-shorthand */
/* eslint-disable vars-on-top */
(function () {
/** The state of things */
let broadcast = { status: 'waiting', streams: 2, rtmp: false };
let subscribers = [];
let renderId;
let session;
let screenSharePublisher;
const SAMPLE_SERVER_BASE_URL = window.location.origin;
const url = new URL(window.location.href);
const params = new URLSearchParams(url.search);
if (!params.get('room')) window.location.replace(`${window.location.origin}/host?room=${generateId()}`);
let bgChoice = null;
/**
* Options for adding OpenTok publisher and subscriber video elements
*/
const insertOptions = {
width: '100%',
height: '100%',
showControls: false,
};
function generateId() {
return Math.floor((1 + Math.random()) * 0x10000).toString();
}
/**
* Get our OpenTok http Key, Session ID, and Token from the JSON embedded
* in the HTML.
*/
const getCredentials = function () {
const el = document.getElementById('credentials');
const credentials = JSON.parse(el.getAttribute('data'));
el.remove();
credentialData = credentials;
return credentials;
};
const showCopiedNotice = function () {
console.log('showing');
const notice = document.getElementById('copyNotice');
notice.classList.remove('opacity-0');
setTimeout(function () {
notice.classList.add('opacity-0');
}, 1500);
};
let credentialData;
/**
* Add a stream to the broadcast
* @param {String} streamId
* @param {String} sessionId - The name of the room
*/
function addStreamToBroadcast(streamId, roomName) {
fetch(`${SAMPLE_SERVER_BASE_URL}/addStream`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ roomName, streamId }),
})
.then(function fetch(res) {
console.log(res);
})
.catch(function (error) {
console.log(error);
});
}
/**
* Start a Experience Composer render
* @param {String} sessionId
* @param {String} roomName - The name of the room
* @param {Number} [bgChoice] - The user choice for background streaming
*/
function startExperienceComposer(sessionId, roomName, bgChoice, round) {
console.log('starting bg' + bgChoice);
fetch(`${SAMPLE_SERVER_BASE_URL}/render`, {
method: 'POST',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({ sessionId, roomName, bgChoice, round }),
})
.then(function fetch(res) {
return res.json();
})
.then(function fetchJson(json) {
console.log(json);
renderId = json.id;
});
}
function stopExperienceComposer(renderId) {
fetch(`${SAMPLE_SERVER_BASE_URL}/render/stop/${renderId}`).then(function fetch(res) {
// return res.json();
console.log('stopped experience composer');
});
}
/**
* Create an OpenTok publisher object
*/
const initPublisher = function () {
const properties = Object.assign(
{
name: 'Host',
insertMode: 'before',
publishAudio: true,
resolution: check1080pCamera() ? '1920x1080' : '1280x720',
},
insertOptions
);
const publisher = OT.initPublisher('hostDivider', properties);
const subscriberData = {
subscriber: publisher,
};
subscribers.push(subscriberData);
return publisher;
};
/**
* Check if you can publish at 1080p
*/
async function check1080pCamera() {
const constraints = {
audio: true,
video: {
width: { min: 1920 },
height: { min: 1080 },
},
};
let stream;
try {
stream = await navigator.mediaDevices.getUserMedia(constraints);
return true;
} catch (err) {
if (err.name === 'OverconstrainedError') {
alert('⚠️ 1080p is not supported on this device!');
return false;
}
return true;
}
}
/**
* Send the broadcast status to everyone connected to the session using
* the OpenTok signaling API
* @param {Object} session
* @param {String} status
* @param {Object} [to] - An OpenTok connection object
*/
const signal = function (session, status, to) {
const signalData = Object.assign({}, { type: 'broadcast', data: status }, to ? { to } : {});
session.signal(signalData, function (error) {
if (error) {
console.log(['signal error (', error.code, '): ', error.message].join(''));
} else {
console.log('signal sent');
}
});
};
const signalBroadcastURL = function (session, url, to) {
console.log('signalBroadcastURL', to, url);
const signalData = Object.assign({}, { type: 'broadcast-url', data: url }, to ? { to } : {});
console.log('signalBroadcastURL#1', signalData);
session.signal(signalData, function (error) {
if (error) {
console.log(['[signalBroadcastURL] - error (', error.code, '): ', error.message].join(''));
} else {
console.log('[signalBroadcastURL] - signal sent');
}
});
};
/**
* Construct the url for viewers to view the broadcast stream
* @param {String} url The CDN url for the m3u8 video stream
* @param {Number} availableAt The time (ms since epoch) at which the stream is available
*/
const getBroadcastUrl = function (url, availableAt) {
return `${window.location.host}/broadcast?url=${url}&availableAt=${availableAt}`;
};
/**
* Set the state of the broadcast and update the UI
*/
const updateStatus = function (session, status) {
const startStopButton = document.getElementById('startStop');
const { url, availableAt } = broadcast;
const playerUrl = getBroadcastUrl(url, availableAt);
const displayUrl = document.getElementById('broadcastURL');
const rtmpActive = document.getElementById('rtmpActive');
const bg = document.getElementById('round-option');
const ecInfo = document.getElementById('ecInfo');
const copyUrl = document.getElementById('copyURL');
broadcast.status = status;
if (status === 'active') {
startStopButton.classList.add('active');
startStopButton.innerHTML = 'End Broadcast';
copyUrl.classList.remove('hidden');
displayUrl.innerHTML = window.location.href.replace('host?', 'hls-viewer?');
ecInfo.classList.add('hidden');
bg.classList.add('hidden');
if (broadcast.rtmp) {
rtmpActive.classList.remove('hidden');
}
} else {
startStopButton.classList.remove('active');
startStopButton.innerHTML = 'Start Broadcast';
rtmpActive.classList.add('hidden');
ecInfo.classList.remove('hidden');
bg.classList.remove('hidden');
copyUrl.classList.add('hidden');
document.getElementById('rtmpLabel').classList.remove('hidden');
document.getElementById('rtmp-options').classList.remove('hidden');
}
signal(session, broadcast.status);
};
// Let the user know that the url has been copied to the clipboard
const validRtmp = function () {
const server = document.getElementById('rtmpServer');
const stream = document.getElementById('rtmpStream');
const serverDefined = !!server.value;
const streamDefined = !!stream.value;
const invalidServerMessage = 'The RTMP server url is invalid. Please update the value and try again.';
const invalidStreamMessage = 'The RTMP stream name must be defined. Please update the value and try again.';
if (serverDefined && !server.checkValidity()) {
document.getElementById('rtmpLabel').classList.add('hidden');
document.getElementById('rtmp-options').classList.add('hidden');
document.getElementById('rtmpError').innerHTML = invalidServerMessage;
document.getElementById('rtmpError').classList.remove('hidden');
return null;
}
if (serverDefined && !streamDefined) {
document.getElementById('rtmpLabel').classList.add('hidden');
document.getElementById('rtmp-options').classList.add('hidden');
document.getElementById('rtmpError').innerHTML = invalidStreamMessage;
document.getElementById('rtmpError').classList.remove('hidden');
return null;
}
document.getElementById('rtmpLabel').classList.remove('hidden');
document.getElementById('rtmp-options').classList.remove('hidden');
document.getElementById('rtmpError').classList.add('hidden');
return { id: generateId(), serverUrl: server.value, streamName: stream.value };
};
const hideRtmpInput = function () {
['rtmpLabel', 'rtmpError', 'rtmpServer', 'rtmpStream', 'rtmp-options'].forEach(function (id) {
document.getElementById(id).classList.add('hidden');
});
};
const showRtmpInput = function () {
['rtmpLabel', 'rtmpError', 'rtmpServer', 'rtmpStream', 'rtmp-options'].forEach(function (id) {
document.getElementById(id).classList.remove('hidden');
});
};
/**
* Make a request to the server to start the broadcast
*/
const startBroadcast = function () {
analytics.log('startBroadcast', 'variationAttempt');
const roomName = params.get('room');
const rtmp = validRtmp();
if (!rtmp) {
analytics.log('startBroadcast', 'variationError');
return;
}
const HLS_LL = document.querySelector('#hls-ll').checked;
const HLS_HD = document.querySelector('#hls-HD').checked;
const HLS_DVR = document.querySelector('#hls-dvr').checked;
const bg0 = document.querySelector('#bg0').checked;
const bg1 = document.querySelector('#bg1').checked;
const bg2 = document.querySelector('#bg2').checked;
const roundyes = document.querySelector('#roundyes').checked;
if (bg0) bgChoice = 0;
if (bg1) bgChoice = 1;
if (bg2) bgChoice = 2;
console.log(`room: ${roomName} bgChoice:${bgChoice} session:${credentialData.sessionId}`);
if (bgChoice !== null) {
startExperienceComposer(credentialData.sessionId, roomName, bgChoice, roundyes);
}
if (HLS_LL && HLS_DVR) alert('DVR is not supported with Low latency HLS, DVR will regular HLS will be selected');
hideRtmpInput();
http
.post('/broadcast/start', {
rtmp: rtmp,
lowLatency: HLS_LL,
fhd: HLS_HD,
dvr: HLS_DVR,
sessionId: credentialData.sessionId,
streamMode: bgChoice !== null ? 'manual' : 'auto',
})
.then(function (broadcastData) {
broadcast = broadcastData;
updateStatus(session, 'active');
signalBroadcastURL(session, broadcast.url, null);
analytics.log('startBroadcast', 'variationSuccess');
})
.catch(function (error) {
console.log(error);
analytics.log('startBroadcast', 'variationError');
});
};
/**
* Make a request to the server to stop the broadcast
*/
const endBroadcast = function () {
bgChoice = null;
http
.post('/broadcast/end', {
sessionId: credentialData.sessionId,
})
.then(function () {
updateStatus(session, 'ended');
showRtmpInput();
analytics.log('endBroadcast', 'variationSuccess');
})
.catch(function (error) {
console.log(error);
analytics.log('endBroadcast', 'variationError');
});
if (renderId) stopExperienceComposer(renderId);
};
/**
* Subscribe to a stream
*/
const subscribe = function (session, stream) {
const properties = Object.assign({ name: 'Guest', insertMode: 'after' }, insertOptions);
const subscriber = session.subscribe(stream, 'hostDivider', properties, function (error) {
if (error) {
console.log(error);
}
});
subscribers.push({ subscriber });
subscriber.on('audioLevelUpdated', audioLevelUpdate);
if (subscribers.length > 3) {
updateBroadcastLayout();
}
};
/**
* Updates the subscriber with its current audio level
* @param {Object} event AudioLevelUpdatedEvent
*/
const audioLevelUpdate = function (event) {
const now = Date.now();
const subData = subscribers.find((f) => f.subscriber.streamId === event.target.streamId);
if (event.audioLevel > 0.2) {
if (!subData.activity) {
subData.activity = {
timestamp: now,
talking: true,
audioLevel: event.audioLevel,
};
} else if (subData.activity.talking && now - subData.activity.timestamp > 1000) {
subData.activity.timestamp = now;
subData.activity.audioLevel = event.audioLevel;
} else if (now - subData.activity.timestamp > 1000) {
// detected audio activity for more than 1s
// for the first time.
subData.activity.talking = true;
subData.activity.audioLevel = event.audioLevel;
}
} else if (subData.activity && now - subData.activity.timestamp > 3000) {
// detected low audio activity for more than 3s
if (subData.activity.talking) {
subData.activity.talking = false;
subData.activity.audioLevel = event.audioLevel;
}
}
subscribers = [...subscribers.filter((f) => f.subscriber.streamId !== event.target.streamId), subData];
};
/**
* Toggle publishing audio/video to allow host to mute
* their video (publishVideo) or audio (publishAudio)
* @param {Object} publisher The OpenTok publisher object
* @param {Object} el The DOM element of the control whose id corresponds to the action
*/
const toggleMedia = function (publisher, el) {
const enabled = el.classList.contains('disabled');
el.classList.toggle('disabled');
publisher[el.id](enabled);
};
/**
* Toggle publishing audio/video to allow host to mute
* their video (publishVideo) or audio (publishAudio)
* @param {Object} publisher The OpenTok publisher object
* @param {Object} el The DOM element of the control whose id corresponds to the action
*/
const toggleScreenShare = function (el) {
const enabled = el.classList.contains('disabled');
el.classList.toggle('disabled');
if (!enabled) {
screenSharePublisher = OT.initPublisher(
'hostDivider',
{ videoSource: 'screen', name: 'HostScreen', insertMode: 'before' },
function (error) {
if (error) {
// Look at error.message to see what went wrong.
} else {
session.publish(screenSharePublisher, function (error) {
if (error) {
// Look error.message to see what went wrong.
}
});
}
}
);
//settig up event listener for when the user clicks on the native browser prompt to stop screen-sharing
screenSharePublisher.on('mediaStopped', function (e) {
const screenShareButton = document.getElementById('screenshare');
screenShareButton.classList.toggle('disabled');
});
screenSharePublisher.on('streamCreated', function (event) {
console.log(event.stream);
if (event.stream.name === 'HostScreen') {
const roomName = params.get('room');
if (bgChoice !== null) {
addStreamToBroadcast(event.stream.id, roomName);
}
}
});
} else {
screenSharePublisher.destroy();
}
};
/**
* Update broadcast layouts
*/
const updateBroadcastLayout = function () {
if (broadcast.status === 'active') {
// streams, type, stylesheet
http
.post('/broadcast/layout', {
streams: subscribers.length,
type: subscribers.length > 3 ? 'custom' : 'bestFit',
sessionId: credentialData.sessionId,
})
.then(function (result) {
console.log(result);
})
.catch(function (error) {
console.log(error);
});
}
};
const setEventListeners = function (session, publisher) {
// Add click handler to the start/stop button
const startStopButton = document.getElementById('startStop');
startStopButton.classList.remove('hidden');
startStopButton.addEventListener('click', function () {
if (broadcast.status === 'waiting' || broadcast.status === 'ended') {
startBroadcast(session);
} else if (broadcast.status === 'active') {
endBroadcast(session);
}
});
document.getElementById('copyURL').addEventListener('click', function () {
showCopiedNotice();
});
// Subscribe to new streams as they're published
session.on('streamCreated', function (event) {
console.log(event.stream);
if (event.stream.name === 'EC' || event.stream.name === 'HostScreen') {
const roomName = params.get('room');
if (bgChoice !== null) {
addStreamToBroadcast(event.stream.id, roomName);
}
return;
}
subscribe(session, event.stream);
if (subscribers.length > 2) {
document.getElementById('videoContainer').classList.add('wrap');
if (broadcast.status === 'active' && subscribers.length <= 3) {
updateBroadcastLayout();
}
}
});
session.on('streamDestroyed', function (event) {
if (event.stream.name === 'EC') return;
subscribers = subscribers.filter((f) => f.subscriber.streamId !== event.stream.id);
if (subscribers.length <= 3) {
document.getElementById('videoContainer').classList.remove('wrap');
if (broadcast.status === 'active' && subscribers.length < 3) {
updateBroadcastLayout();
}
}
});
// Signal the status of the broadcast when requested
session.on('signal:broadcast', function (event) {
console.log('pinging broadcast status');
if (event.data === 'status') {
signal(session, broadcast.status, event.from);
if (broadcast.status === 'active') {
signalBroadcastURL(session, broadcast.url, event.from);
}
}
});
document.getElementById('videoInputs').addEventListener('change', (e) => {
onVideoSourceChanged(e, publisher);
});
document.getElementById('audioInputs').addEventListener('change', (e) => {
onAudioSourceChanged(e, publisher);
});
navigator.mediaDevices.ondevicechange = () => {
refreshDeviceList(publisher);
};
publisher.on('accessAllowed', () => {
refreshDeviceList(publisher);
});
document.getElementById('publishVideo').addEventListener('click', function () {
toggleMedia(publisher, this);
});
document.getElementById('publishAudio').addEventListener('click', function () {
toggleMedia(publisher, this);
});
document.getElementById('screenshare').addEventListener('click', function () {
toggleScreenShare(this);
});
};
const addPublisherControls = function (publisher) {
const publisherContainer = document.getElementById(publisher.element.id);
const el = document.createElement('div');
const controls = [
'<div>',
'<div class="btn-group">',
'<div class="publisher-controls-container">',
'<div id="publishVideo" class="control video-control"></div>',
'<select style="width:15px" class="btn btn-secondary dropdown-toggle dropdown-toggle-split" id="videoInputs" data-bs-toggle="dropdown" aria-expanded="false" data-bs-reference="parent">',
'<option selected class="dropdown-item"></option>',
'</select>',
'</div>',
'</div>',
'<div style="margin-left: 40px" class="btn-group">',
'<div class="publisher-controls-container">',
'<div id="publishAudio" class="control audio-control"></div>',
'<select style="width:15px" class="btn btn-secondary dropdown-toggle dropdown-toggle-split" id="audioInputs" data-bs-toggle="dropdown" aria-expanded="false" data-bs-reference="parent">',
'<option selected class="dropdown-item"></option>',
'</select>',
'</div>',
'</div>',
'<div style="margin-top:100px; height:40px" class="publisher-controls-container">',
'<div id="screenshare" class="control screenshare"></div>',
'</div>',
'</div>',
].join('\n');
el.innerHTML = controls;
publisherContainer.appendChild(el.firstChild);
};
/**
* The host starts publishing and signals everyone else connected to the
* session so that they can start publishing and/or subscribing.
* @param {Object} session The OpenTok session
* @param {Object} publisher The OpenTok publisher object
*/
const publishAndSubscribe = function (session, publisher) {
session.publish(publisher);
addPublisherControls(publisher);
setEventListeners(session, publisher);
};
const refreshDeviceList = (pub) => {
console.log('refreshDeviceList');
listVideoInputs().then((devices) => {
console.log(devices);
const videoSelect = document.getElementById('videoInputs');
videoSelect.innerHTML = '';
const currentVideoSource = pub.getVideoSource();
if (currentVideoSource) {
// Select Input
const currentVideoOption = document.createElement('option');
//disabledOption.disabled = true;
currentVideoOption.innerText = currentVideoSource?.track?.label;
currentVideoOption.classList.add('dropdown-item');
currentVideoOption.value = currentVideoSource.track?.label;
currentVideoOption.selected = true;
videoSelect.appendChild(currentVideoOption);
}
for (let i = 0; i < devices.length; i += 1) {
if (devices[i].deviceId != currentVideoSource.deviceId) {
const deviceOption = document.createElement('option');
deviceOption.classList.add('dropdown-item');
deviceOption.innerText = devices[i].label || `Video Input ${i + 1}`;
// deviceOption.value = `video-source-${i}`;
deviceOption.value = devices[i].label;
videoSelect.appendChild(deviceOption);
}
}
if (devices.length === 0) {
const deviceOption = document.createElement('option');
deviceOption.innerText = 'Default Video Input';
deviceOption.value = `default-video`;
videoSelect.appendChild(deviceOption);
}
});
listAudioInputs().then((devices) => {
const audioSelect = document.getElementById('audioInputs');
audioSelect.innerHTML = '';
const currentAudioSource = pub.getAudioSource();
console.log(devices);
// Select Input
const currentAudioOption = document.createElement('option');
currentAudioOption.innerText = currentAudioSource?.label;
currentAudioOption.value = currentAudioSource?.label;
currentAudioOption.selected = true;
audioSelect.appendChild(currentAudioOption);
for (let i = 0; i < devices.length; i += 1) {
if (devices[i].label != currentAudioSource.label) {
const deviceOption = document.createElement('option');
deviceOption.innerText = devices[i].label || `Audio Input ${i + 1}`;
deviceOption.value = devices[i].label;
audioSelect.appendChild(deviceOption);
}
}
if (devices.length === 0) {
const deviceOption = document.createElement('option');
deviceOption.innerText = 'Default Audio Input';
deviceOption.value = `default-audio`;
audioSelect.appendChild(deviceOption);
}
});
};
const onVideoSourceChanged = async (event, publisher) => {
console.log(event);
const labelToFind = event.target.value;
const videoDevices = await listVideoInputs();
const deviceId = videoDevices.find((e) => e.label === labelToFind)?.deviceId;
if (deviceId != null) {
publisher.setVideoSource(deviceId);
}
};
const onAudioSourceChanged = async (event, publisher) => {
const labelToFind = event.target.value;
const audioDevices = await listAudioInputs();
const deviceId = audioDevices.find((e) => e.label === labelToFind)?.deviceId;
if (deviceId != null) {
publisher.setAudioSource(deviceId);
}
};
const listAudioInputs = async () => {
try {
const devices = await listDevices();
const filteredDevices = devices.filter((device) => device.kind === 'audioInput');
return Promise.resolve(filteredDevices);
} catch (error) {
return Promise.reject(error);
}
};
const listVideoInputs = async () => {
try {
const devices = await listDevices();
const filteredDevices = devices.filter((device) => device.kind === 'videoInput');
return Promise.resolve(filteredDevices);
} catch (error) {
return Promise.reject(error);
}
};
const listDevices = () => {
return new Promise((resolve, reject) => {
OT.getDevices((error, devices) => {
if (error) {
reject(error);
} else {
resolve(devices);
}
});
});
};
const init = function () {
const clipboard = new ClipboardJS('#copyURL');
const credentials = getCredentials();
const props = { connectionEventsSuppressed: true };
session = OT.initSession(credentials.apiKey, credentials.sessionId, props);
const publisher = initPublisher();
session.connect(credentials.token, function (error) {
if (error) {
console.log(error);
analytics.init(session);
analytics.log('initialize', 'variationAttempt');
analytics.log('initialize', 'variationError');
} else {
publishAndSubscribe(session, publisher);
analytics.init(session);
analytics.log('initialize', 'variationAttempt');
analytics.log('initialize', 'variationSuccess');
}
});
};
document.addEventListener('DOMContentLoaded', init);
})();