-
Notifications
You must be signed in to change notification settings - Fork 35
/
index.js
387 lines (335 loc) · 10.7 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
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
/*
* Main functions: core call infrastructure, setting up the callframe and event listeners, creating room URL, and joining
* Event listener callbacks: fired when specified Daily events execute
* Call panel button functions: participant controls
*/
/* Main functions */
let callFrame, room;
async function createCallframe() {
const callWrapper = document.getElementById('wrapper');
callFrame = await window.DailyIframe.createFrame(callWrapper);
callFrame
.on('loaded', showEvent)
.on('started-camera', showEvent)
.on('camera-error', showEvent)
.on('joining-meeting', toggleLobby)
.on('joined-meeting', handleJoinedMeeting)
.on('left-meeting', handleLeftMeeting);
const roomURL = document.getElementById('url-input');
const joinButton = document.getElementById('join-call');
const createButton = document.getElementById('create-and-start');
roomURL.addEventListener('input', () => {
if (roomURL.checkValidity()) {
joinButton.classList.add('valid');
joinButton.classList.remove('disabled-button');
joinButton.removeAttribute('disabled');
createButton.classList.add('disabled-button');
} else {
joinButton.classList.remove('valid');
}
});
roomURL.addEventListener('keyup', (event) => {
if (event.keyCode === 13) {
event.preventDefault();
joinButton.click();
}
});
}
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"}
}
async function createRoomAndStart() {
const createAndStartButton = document.getElementById('create-and-start');
const copyUrl = document.getElementById('copy-url');
const errorTitle = document.getElementById('error-title');
const errorDescription = document.getElementById('error-description');
createAndStartButton.innerHTML = 'Loading...';
room = await createRoom();
if (!room) {
errorTitle.innerHTML = 'Error creating room';
errorDescription.innerHTML =
"If you're developing locally, please check the README instructions.";
toggleMainInterface();
toggleError();
}
copyUrl.value = room.url;
showDemoCountdown();
try {
callFrame.join({
url: room.url,
showLeaveButton: true,
});
} catch (e) {
toggleError();
console.error(e);
}
}
async function joinCall() {
const url = document.getElementById('url-input').value;
const copyUrl = document.getElementById('copy-url');
copyUrl.value = url;
try {
await callFrame.join({
url: url,
showLeaveButton: true,
//TODO: add an owner token to use live streaming
// token: <token>,
});
} catch (e) {
if (
e.message === "can't load iframe meeting because url property isn't set"
) {
toggleMainInterface();
console.log('empty URL');
}
toggleError();
console.error(e);
}
}
/* Event listener callbacks and helpers */
function showEvent(e) {
console.log('callFrame event', e);
}
function toggleHomeScreen() {
const homeScreen = document.getElementById('start-container');
homeScreen.classList.toggle('hide');
}
function toggleLobby() {
const callWrapper = document.getElementById('wrapper');
callWrapper.classList.toggle('in-lobby');
toggleHomeScreen();
}
function toggleControls() {
const callControls = document.getElementById('call-controls-wrapper');
callControls.classList.toggle('hide');
}
function toggleCallStyling() {
const callWrapper = document.getElementById('wrapper');
const createAndStartButton = document.getElementById('create-and-start');
createAndStartButton.innerHTML = 'Create room and start';
callWrapper.classList.toggle('in-call');
}
function toggleError() {
const errorMessage = document.getElementById('error-message');
errorMessage.classList.toggle('error-message');
toggleControls();
toggleCallStyling();
}
function toggleMainInterface() {
toggleHomeScreen();
toggleControls();
toggleCallStyling();
}
function handleJoinedMeeting() {
toggleLobby();
toggleMainInterface();
}
function handleLeftMeeting() {
toggleMainInterface();
}
function resetErrorDesc() {
const errorTitle = document.getElementById('error-title');
const errorDescription = document.getElementById('error-description');
errorTitle.innerHTML = 'Incorrect room URL';
errorDescription.innerHTML =
'Meeting link entered is invalid. Please update the room URL.';
}
function tryAgain() {
toggleError();
toggleMainInterface();
resetErrorDesc();
}
/* Call panel button functions */
function copyUrl() {
const url = document.getElementById('copy-url');
const copyButton = document.getElementById('copy-url-button');
url.select();
document.execCommand('copy');
copyButton.innerHTML = '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 toggleFullscreen() {
callFrame.requestFullscreen();
}
// To use live streaming, the room URL should use the format:
// https://your-daily-domain.daily.co/room-name?t=your-owner-meeting-token
function startLiveStreaming() {
// This should be in the format rtmp://RTMP_ENDPOINT/STREAM_KEY
// or rtmps://RTMP_ENDPOINT/STREAM_KEY
console.log('starting!!!');
const rtmpUrl = 'rtmp://RTMP_ENDPOINT/STREAM_KEY';
callFrame.startLiveStreaming({
rtmpUrl,
layout: {
preset: 'custom',
composition_params: {
'videoSettings.showParticipantLabels': true,
},
/* optional: sessions assets must be included in startLiveStreaming() even if they aren't used until an updateLiveStreaming() call
session asset images *must* be a .png
*/
session_assets: {
'images/dailyLogo': 'https://docs.daily.co/assets/generic-meta.png',
},
},
});
}
function updateLiveStreaming() {
console.log('updating!!!');
callFrame.updateLiveStreaming({
layout: {
preset: 'custom',
composition_params: {
mode: 'pip',
showImageOverlay: true,
'image.assetName': 'dailyLogo',
'image.aspectRatio': 1,
'image.position': 'bottom-left',
'image.opacity': 0.7,
'image.height_vh': 0.2,
'image.margin_vh': 0.01,
showTextOverlay: true,
'text.align_horizontal': 'right',
'text.align_vertical': 'bottom',
'text.offset_x': -20,
'text.fontFamily': 'PermanentMarker',
'text.content': 'Hello from Daily!',
},
},
});
}
function stopLiveStreaming() {
console.log('stopping!!!');
callFrame.stopLiveStreaming();
}
let toastKey = 0;
function showToast(e) {
// prevent default form behavior
e.preventDefault();
// get input value from form submit event
const toastText = e.target[0].value;
// send
callFrame.updateLiveStreaming({
layout: {
preset: 'custom',
composition_params: {
'toast.text': toastText,
'toast.color': 'rgba(215, 50, 110, 0.8)',
'toast.text.fontFamily': 'Bitter',
'toast.duration_secs': 3,
'toast.text.fontSize_pct': 150,
'toast.text.fontWeight': '400',
'toast.key': toastKey,
},
},
});
toastKey++;
}
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`;
}
/* Other helper functions */
// Populates 'network info' with information info from daily-js
async function updateNetworkInfoDisplay() {
const videoSend = document.getElementById('video-send'),
videoReceive = document.getElementById('video-receive'),
packetSend = document.getElementById('packet-send'),
packetReceive = document.getElementById('packet-receive');
let statsInfo = await callFrame.getNetworkStats();
videoSend.innerHTML = `${Math.floor(
statsInfo.stats.latest.videoSendBitsPerSecond / 1000
)} kb/s`;
videoReceive.innerHTML = `${Math.floor(
statsInfo.stats.latest.videoRecvBitsPerSecond / 1000
)} kb/s`;
packetSend.innerHTML = `${Math.floor(
statsInfo.stats.worstVideoSendPacketLoss * 100
)}%`;
packetReceive.innerHTML = `${Math.floor(
statsInfo.stats.worstVideoRecvPacketLoss * 100
)}%`;
}
function showRoomInput() {
const urlInput = document.getElementById('url-input');
const urlClick = document.getElementById('url-click');
const urlForm = document.getElementById('url-form');
urlClick.classList.remove('show');
urlClick.classList.add('hide');
urlForm.classList.remove('hide');
urlForm.classList.add('show');
urlInput.focus();
}
function showDemoCountdown() {
const countdownDisplay = document.getElementById('demo-countdown');
if (!window.expiresUpdate) {
window.expiresUpdate = setInterval(() => {
let exp = room && room.config && room.config.exp;
if (exp) {
let seconds = Math.floor((new Date(exp * 1000) - Date.now()) / 1000);
let minutes = Math.floor(seconds / 60);
let remainingSeconds = Math.floor(seconds % 60);
countdownDisplay.innerHTML = `Demo expires in ${minutes}:${
remainingSeconds > 10 ? remainingSeconds : '0' + remainingSeconds
}`;
}
}, 1000);
}
}