-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
187 lines (162 loc) · 4.83 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
'use strict';
/**
* Load Twilio configuration from .env config file - the following environment
* variables should be set:
* process.env.TWILIO_ACCOUNT_SID
* process.env.TWILIO_API_KEY
* process.env.TWILIO_API_SECRET
*/
require('dotenv').load();
const express = require('express');
const http = require('http');
const path = require('path');
const axios = require('axios');
// Max. period that a Participant is allowed to be in a Room (currently 14400 seconds or 4 hours)
const MAX_ALLOWED_SESSION_DURATION = 14400;
const dailyAPIURL = `https://api.daily.co/v1`;
// Create Express webapp.
const app = express();
// Set up the paths for the examples.
[
'bandwidthconstraints',
'codecpreferences',
'dominantspeaker',
'localvideofilter',
'localvideosnapshot',
'mediadevices',
'networkquality',
'reconnection',
'screenshare',
'localmediacontrols',
'remotereconnection',
'datatracks',
'manualrenderhint',
'autorenderhint'
].forEach(example => {
const examplePath = path.join(__dirname, `../examples/${example}/public`);
app.use(`/${example}`, express.static(examplePath));
});
// Set up the path for the quickstart.
const quickstartPath = path.join(__dirname, '../quickstart/public');
app.use('/quickstart', express.static(quickstartPath));
// Set up the path for the examples page.
const examplesPath = path.join(__dirname, '../examples');
app.use('/examples', express.static(examplesPath));
/**
* Default to the Quick Start application.
*/
app.get('/', (request, response) => {
response.redirect('/quickstart');
});
/**
* Generate an Access Token for a chat application user.
* Retrieve an existing room or create one with the given
* name if it does not already exist.
*/
app.get('/token', async function (request, response) {
const query = request.query;
const userName = query.identity;
const roomName = query.roomName;
let roomData = await getRoom(roomName);
if (!roomData) {
roomData = await createRoom(roomName);
}
const token = await getMeetingToken(roomName, userName);
const res = {
token: token,
roomURL: roomData.url,
};
response.send(JSON.stringify(res));
});
// Create http server and run it.
const server = http.createServer(app);
const port = process.env.PORT || 3000;
server.listen(port, function() {
console.log('Express server running on *:' + port);
});
// getRoom() retrieves a room by name, if one exists.
async function getRoom(roomName) {
const apiKey = process.env.DAILY_API_KEY;
// Prepare our headers, containing our Daily API key
const headers = {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
};
const url = `${dailyAPIURL}/rooms/${roomName}`;
const errMsg = "Failed to get room information."
let res;
try {
res = await axios
.get(url, {
headers: headers,
})
} catch(error) {
if (error.response?.status === 404) {
return null;
}
throw new Error(`${errMsg}: ${error})`);
}
if (res.status !== 200 || !res.data) {
console.error('unexpected room retrieval response:', res);
throw new Error(errMsg);
}
return res.data;
}
async function createRoom(roomName) {
const apiKey = process.env.DAILY_API_KEY;
// Prepare our desired room properties.
const req = {
name: roomName,
privacy: 'private',
properties: {
exp: Math.floor(Date.now() / 1000) + MAX_ALLOWED_SESSION_DURATION,
// Start right away in SFU mode
sfu_switchover: 0.5,
},
};
// Prepare our headers, containing our Daily API key
const headers = {
Authorization: `Bearer ${apiKey}`,
'Content-Type': 'application/json',
};
const url = `${dailyAPIURL}/rooms/`;
const data = JSON.stringify(req);
const roomErrMsg = 'failed to create room';
const res = await axios
.post(url, data, {
headers: headers,
})
.catch((error) => {
console.error(roomErrMsg, error);
throw new Error(`${roomErrMsg}: ${error})`);
});
if (res.status !== 200 || !res.data) {
console.error('unexpected room creation response:', res);
throw new Error(roomErrMsg);
}
return res.data;
}
// getMeetingToken() obtains a meeting token for a room from Daily
async function getMeetingToken(roomName, userName) {
const req = {
properties: {
room_name: roomName,
user_name: userName,
exp: Math.floor(Date.now() / 1000) + MAX_ALLOWED_SESSION_DURATION,
},
};
const data = JSON.stringify(req);
const headers = {
Authorization: `Bearer ${process.env.DAILY_API_KEY}`,
'Content-Type': 'application/json',
};
const url = `${dailyAPIURL}/meeting-tokens/`;
const errMsg = 'failed to create meeting token';
const res = await axios.post(url, data, { headers }).catch((error) => {
throw new Error(`${errMsg}: ${error})`);
});
if (res.status !== 200) {
throw new Error(`${errMsg}: got status ${res.status})`);
}
return res.data?.token;
}