forked from daily-demos/prebuilt-ui
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
334 lines (292 loc) · 10.2 KB
/
index.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
/*
* Main functions: core call infrastructure, letting setting up the room, event listeners, and joining
* Event listener callbacks: fired when specified Daily events execute
* Call panel button functions: participant controls
*/
/* Main functions */
// Creates the callframe
// Defines event listeners on Daily events
// Assigns an event listener to the input field to change the join button color
async function setup() {
callFrame = await window.DailyIframe.createFrame(
document.getElementById('callframe'),
{
iframeStyle: {
position: 'absolute',
top: '0',
left: '0',
width: '100%',
height: '90%',
border: '0',
},
}
);
callFrame
.on('loaded', showEvent)
.on('started-camera', showEvent)
.on('camera-error', showEvent)
.on('joining-meeting', showEvent)
.on('joined-meeting', showCallDisplay)
.on('recording-started', showEvent)
.on('recording-stopped', resetRecordingButton)
.on('recording-stats', showEvent)
.on('recording-error', showEvent)
.on('app-message', showEvent)
.on('input-event', showEvent)
.on('error', showEvent)
.on('participant-joined', updateParticipantInfoDisplay)
.on('participant-updated', updateParticipantInfoDisplay)
.on('participant-left', updateParticipantInfoDisplay)
.on('left-meeting', hideCallDisplay);
let roomURL = document.getElementById('room-url');
const joinButton = document.getElementsByClassName('join-call')[0];
roomURL.addEventListener('input', () => {
if (roomURL.checkValidity()) {
joinButton.classList.add('valid');
} else {
joinButton.classList.remove('valid');
}
});
}
async function createRoom() {
// This endpoint is using the proxy as outlined in netlify.toml
const newRoomEndpoint = `${window.location.origin}/api/rooms`;
// we'll add 30 min expiry (exp) so rooms won't linger too long on your account
// we'll also turn on chat (enable_chat)
// see other available options at https://docs.daily.co/reference#create-room
const exp = Math.round(Date.now() / 1000) + 60 * 30;
const options = {
properties: {
exp: exp,
enable_chat: true,
},
};
try {
let response = await fetch(newRoomEndpoint, {
method: 'POST',
body: JSON.stringify(options),
mode: 'cors',
}),
room = await response.json();
return room;
} catch (e) {
console.error(e);
}
// Comment out the above and uncomment the below, using your own URL
// if you prefer to test with a hardcoded room
// return {url: "https://your-domain.daily.co/hello"}
}
// Creates a temporary Daily demo room
// Assigns the demo room URL to the input value
// Changes the color of the 'join' button once a room has been created
async function createDemoRoom() {
const createButton = document.getElementById('create-button');
const joinButton = document.getElementsByClassName('join-call')[0];
const roomURL = document.getElementById('room-url');
createButton.innerHTML = 'Creating room...';
room = await createRoom();
// ownerLink = await createMtgLinkWithToken(room, {
// is_owner: true,
// enable_recording: 'local',
// });
roomURL.value = room.url;
joinButton.classList.toggle('turn-green');
createButton.innerHTML = 'Copy room link';
createButton.setAttribute('onclick', 'copyLink()');
displayDemoRoomTimer();
}
// Joins Daily call
// Passes the value in the 'room-url' input to callFrame.join
async function joinCall() {
const roomURL = document.getElementById('room-url');
await callFrame.join({
url: roomURL.value,
showLeaveButton: true,
});
}
async function saveUsername() {
const username = document.getElementById('username');
await callFrame.setUserName(username.value, { thisMeetingOnly: false });
}
/* Event listener callbacks */
// Logs the Daily event to the console
function showEvent(e) {
console.log('callFrame event', e);
}
// 'joined-meeting'
// Displays the call
// Changes instructional text and button to "copy" instead of "create"
// Hides the join call button
// Calls functions to update network stats and display demo room
function showCallDisplay(e) {
const callPanel = document.getElementsByClassName('call-panel')[0],
joinButton = document.getElementsByClassName('join-call')[0],
instructionText = document.getElementById('instruction-text');
showEvent(e);
setInterval(updateNetworkInfoDisplay, 5000);
callPanel.classList.remove('hide');
callPanel.classList.add('show');
instructionText.innerHTML = 'Copy and share the URL to invite others';
joinButton.classList.remove('button');
joinButton.classList.add('hide');
}
// 'left-meeting'
// Hides the call once the participant has exited
// Changes text back to "create" instead of copy
// Clears input and button values
// Restores join call and create demo buttons
function hideCallDisplay(e) {
const expiresCountdown = document.getElementsByClassName(
'expires-countdown'
)[0],
callPanel = document.getElementsByClassName('call-panel')[0],
instructionText = document.getElementById('instruction-text'),
topButton = document.getElementById('create-button'),
joinButton = document.getElementsByClassName('join-call')[0];
showEvent(e);
expiresCountdown.classList.toggle('hide');
callPanel.classList.remove('show');
callPanel.classList.add('hide');
instructionText.innerHTML =
'To get started, enter an existing room URL or create a temporary demo room';
joinButton.classList.remove('hide');
joinButton.classList.add('button');
topButton.innerHTML = 'Create demo room';
topButton.setAttribute('onclick', 'createDemoRoom()');
}
// Changes the text on the recording button
function resetRecordingButton(e) {
const recordingButton = document.getElementById('recording-button');
showEvent(e);
recordingButton.setAttribute('onclick', 'callFrame.startRecording()');
recordingButton.innerHTML = 'Start recording';
}
/* Call panel button functions */
function copyLink() {
const link = document.getElementById('room-url');
link.select();
document.execCommand('copy');
console.log('copied');
}
function toggleCamera() {
callFrame.setLocalVideo(!callFrame.participants().local.video);
}
function toggleMic() {
callFrame.setLocalAudio(!callFrame.participants().local.audio);
}
function toggleScreenshare() {
let participants = callFrame.participants();
const shareButton = document.getElementById('share-button');
if (participants.local) {
if (!participants.local.screen) {
callFrame.startScreenShare();
shareButton.innerHTML = 'Stop screenshare';
} else if (participants.local.screen) {
callFrame.stopScreenShare();
shareButton.innerHTML = 'Share screen';
}
}
}
function toggleLocalVideo() {
const localVideoButton = document.getElementById('local-video-button');
const currentlyShown = callFrame.showLocalVideo();
callFrame.setShowLocalVideo(!currentlyShown);
localVideoButton.innerHTML = `${
currentlyShown ? 'Show' : 'Hide'
} local video`;
}
function toggleParticipantsBar() {
const participantsBarButton = document.getElementById(
'participants-bar-button'
);
const currentlyShown = callFrame.showParticipantsBar();
callFrame.setShowParticipantsBar(!currentlyShown);
participantsBarButton.innerHTML = `${
currentlyShown ? 'Show' : 'Hide'
} participants bar`;
}
function toggleRecording() {
const recordingButton = document.getElementById('recording-button');
callFrame.startRecording();
recordingButton.setAttribute('onclick', 'callFrame.stopRecording()');
recordingButton.innerHTML = 'Stop recording';
}
function updateBackground() {
const backgrounds = [
'balloons.jpg',
'confetti.jpg',
'dessert.jpg',
'fireworks.jpg',
'',
];
document.body.style.backgroundImage = `url('./assets/backgrounds/${
backgrounds[Math.ceil(Math.random() * (backgrounds.length - 1))]
}')`;
}
function unsubscribeTracks() {
callFrame.setSubscribeToTracksAutomatically(false);
const tracksButton = document.getElementById('tracks-button');
tracksButton.setAttribute('onclick', 'subscribeTracks()');
tracksButton.innerHTML = 'Subscribe to video and audio';
}
function subscribeTracks() {
callFrame.setSubscribeToTracksAutomatically(true);
const tracksButton = document.getElementById('tracks-button');
tracksButton.setAttribute('onclick', 'unsubscribeTracks()');
tracksButton.innerHTML = 'Unsubscribe from video and audio';
}
/* Other helper functions */
// Populates 'network info' with information info from daily-js
async function updateNetworkInfoDisplay() {
let networkInfo = document.getElementsByClassName('network-info')[0],
statsInfo = await callFrame.getNetworkStats();
networkInfo.innerHTML = `
<li>
Video send:
${Math.floor(statsInfo.stats.latest.videoSendBitsPerSecond / 1000)} kb/s
</li>
<li>
Video recv:
${Math.floor(statsInfo.stats.latest.videoRecvBitsPerSecond / 1000)} kb/s
</li>
<li>
Worst send packet loss:
${Math.floor(statsInfo.stats.worstVideoSendPacketLoss * 100)}%
</li>
<li>Worst recv packet loss:
${Math.floor(statsInfo.stats.worstVideoRecvPacketLoss * 100)}%
</li>
`;
document.getElementsByClassName('loading-network')[0].classList.add('hide');
}
// Loops through callFrame.participants() to list participants on the call
function updateParticipantInfoDisplay(e) {
showEvent(e);
let meetingParticipantsInfo = document.getElementById(
'meeting-participants-info'
),
participants = callFrame.participants(),
participantsList = '';
for (var id in participants) {
let p = participants[id];
participantsList += `
<li>${p.user_name || 'Guest'}</li>
`;
}
meetingParticipantsInfo.innerHTML = participantsList;
}
// Displays a countdown timer for the demo room if a demo room has been created
function displayDemoRoomTimer() {
if (!window.expiresUpdate) {
window.expiresUpdate = setInterval(() => {
let exp = room && room.config && room.config.exp;
if (exp) {
document.getElementsByClassName('expires-countdown')[0].innerHTML = `
<em>⏳ Heads up! Your demo room expires in
${Math.floor((new Date(exp * 1000) - Date.now()) / 1000)}
seconds ⏳</em>
`;
}
}, 1000);
}
}