forked from twilio/twilio-live-interactive-video
-
Notifications
You must be signed in to change notification settings - Fork 0
/
create-stream.js
379 lines (342 loc) · 10.3 KB
/
create-stream.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
/* global Twilio Runtime */
'use strict';
const querystring = require('querystring');
const AccessToken = Twilio.jwt.AccessToken;
const VideoGrant = AccessToken.VideoGrant;
const ChatGrant = AccessToken.ChatGrant;
const SyncGrant = AccessToken.SyncGrant;
const MAX_ALLOWED_SESSION_DURATION = 14400;
module.exports.handler = async (context, event, callback) => {
const {
ACCOUNT_SID,
TWILIO_API_KEY_SID,
TWILIO_API_KEY_SECRET,
CONVERSATIONS_SERVICE_SID,
BACKEND_STORAGE_SYNC_SERVICE_SID,
SYNC_SERVICE_NAME_PREFIX,
DOMAIN_NAME,
DISABLE_CHAT,
} = context;
const authHandler = require(Runtime.getAssets()['/auth.js'].path);
authHandler(context, event, callback);
const common = require(Runtime.getAssets()['/common.js'].path);
const { axiosClient } = common(context, event, callback);
const { user_identity, stream_name } = event;
let response = new Twilio.Response();
response.appendHeader('Content-Type', 'application/json');
if (!user_identity) {
response.setStatusCode(400);
response.setBody({
error: {
message: 'missing user_identity',
explanation: 'The user_identity parameter is missing.',
},
});
return callback(null, response);
}
if (!stream_name) {
response.setStatusCode(400);
response.setBody({
error: {
message: 'missing stream_name',
explanation: 'The stream_name parameter is missing.',
},
});
return callback(null, response);
}
let room, playerStreamer, mediaProcessor, streamSyncService, streamSyncClient, conversation;
const client = context.getTwilioClient();
try {
room = await client.video.rooms.create({
uniqueName: stream_name,
type: 'group',
statusCallback: 'https://' + DOMAIN_NAME + '/rooms-webhook',
});
} catch (e) {
console.error(e);
response.setStatusCode(500);
response.setBody({
error: {
message: 'error creating room',
explanation: e.message,
},
});
return callback(null, response);
}
try {
const maxStreamDuration = 60 * 30; // 30 minutes
// Create playerStreamer
playerStreamer = await axiosClient('PlayerStreamers', {
method: 'post',
data: querystring.stringify({
MaxDuration: maxStreamDuration,
Video: true,
}),
});
// Create mediaProcessor
mediaProcessor = await axiosClient('MediaProcessors', {
method: 'post',
data: querystring.stringify({
MaxDuration: maxStreamDuration,
Extension: context.MEDIA_EXTENSION,
ExtensionContext: JSON.stringify({
room: { name: room.sid },
outputs: [playerStreamer.data.sid],
resolution: '1920x1080',
}),
}),
});
console.log(
'created stream: ',
JSON.stringify({
stream_url: playerStreamer.data.playback_url,
playerStreamerSid: playerStreamer.data.sid,
mediaProcessorSid: mediaProcessor.data.sid,
})
);
} catch (e) {
console.error(e);
response.setStatusCode(500);
response.setBody({
error: {
message: 'error creating stream',
explanation: e.message,
},
});
return callback(null, response);
}
// Create stream sync service
try {
streamSyncService = await client.sync.services.create({
friendlyName: SYNC_SERVICE_NAME_PREFIX + 'Stream ' + room.sid,
aclEnabled: true,
webhookUrl: 'https://' + DOMAIN_NAME + '/sync-webhook',
reachabilityWebhooksEnabled: true,
reachabilityDebouncingEnabled: true, // To prevent disconnect event when connections are rebalanced
});
streamSyncClient = await client.sync.services(streamSyncService.sid);
} catch (e) {
console.error(e);
response.setStatusCode(500);
response.setBody({
error: {
message: 'error creating stream sync service',
explanation: e.message,
},
});
return callback(null, response);
}
// Add stream to streams map
try {
const backendStorageSyncService = client.sync.services(BACKEND_STORAGE_SYNC_SERVICE_SID);
await backendStorageSyncService.syncMaps('streams').syncMapItems.create({
key: room.sid,
data: {
sync_service_sid: streamSyncService.sid,
player_streamer_sid: playerStreamer.data.sid,
media_processor_sid: mediaProcessor.data.sid,
},
});
} catch (e) {
console.error(e);
response.setStatusCode(500);
response.setBody({
error: {
message: 'error adding stream to streams map',
explanation: e.message,
},
});
return callback(null, response);
}
const speakersMapName = `speakers`;
// Create speakers map
try {
await streamSyncClient.syncMaps.create({
uniqueName: speakersMapName,
});
} catch (e) {
console.error(e);
response.setStatusCode(500);
response.setBody({
error: {
message: 'error creating speakers map',
explanation: e.message,
},
});
return callback(null, response);
}
// Add the host to the speakers map when the stream is created so that:
//
// 1. The speakers map is gauranteed to contain the host before any user connects to the stream.
// 2. We don't need a separate way to keep track of who the host is.
//
// There is only one host and it is the user that creates the stream. Other users are added to
// the speakers map in rooms-webhook when they connect to the video room.
try {
await streamSyncClient.syncMaps('speakers').syncMapItems.create({
key: user_identity,
data: { host: true },
});
} catch (e) {
console.error(e);
response.setStatusCode(500);
response.setBody({
error: {
message: 'error adding host to speakers map',
explanation: e.message,
},
});
return callback(null, response);
}
// Give user read access to speakers map
try {
await streamSyncClient
.syncMaps(speakersMapName)
.syncMapPermissions(user_identity)
.update({ read: true, write: false, manage: false });
} catch (e) {
response.setStatusCode(500);
response.setBody({
error: {
message: 'error adding read access to speakers map',
explanation: e.message,
},
});
return callback(null, response);
}
const raisedHandsMapName = `raised_hands`;
// Create raised hands map
try {
await streamSyncClient.syncMaps.create({
uniqueName: raisedHandsMapName,
});
} catch (e) {
console.error(e);
response.setStatusCode(500);
response.setBody({
error: {
message: 'error creating raised hands map',
explanation: e.message,
},
});
return callback(null, response);
}
// Give user read access to raised hands map
try {
await streamSyncClient
.syncMaps(raisedHandsMapName)
.syncMapPermissions(user_identity)
.update({ read: true, write: false, manage: false });
} catch (e) {
response.setStatusCode(500);
response.setBody({
error: {
message: 'error adding read access to raised hands map',
explanation: e.message,
},
});
return callback(null, response);
}
const viewersMapName = `viewers`;
// Create viewers map
try {
await streamSyncClient.syncMaps.create({
uniqueName: viewersMapName,
});
} catch (e) {
console.error(e);
response.setStatusCode(500);
response.setBody({
error: {
message: 'error creating viewers map',
explanation: e.message,
},
});
return callback(null, response);
}
// Give user read access to viewers map
try {
await streamSyncClient
.syncMaps(viewersMapName)
.syncMapPermissions(user_identity)
.update({ read: true, write: false, manage: false });
} catch (e) {
response.setStatusCode(500);
response.setBody({
error: {
message: 'error adding read access to viewers map',
explanation: e.message,
},
});
return callback(null, response);
}
if (DISABLE_CHAT !== 'true') {
const conversationsClient = client.conversations.services(CONVERSATIONS_SERVICE_SID);
try {
// Here we add a timer to close the conversation after the maximum length of a room (24 hours).
// This helps to clean up old conversations since there is a limit that a single participant
// can not be added to more than 1,000 open conversations.
conversation = await conversationsClient.conversations.create({
uniqueName: room.sid,
'timers.closed': 'P1D',
});
} catch (e) {
console.error(e);
response.setStatusCode(500);
response.setBody({
error: {
message: 'error creating conversation',
explanation: 'Something went wrong when creating a conversation.',
},
});
return callback(null, response);
}
try {
// Add participant to conversation
await conversationsClient.conversations(room.sid).participants.create({ identity: user_identity });
} catch (e) {
// Ignore "Participant already exists" error (50433)
if (e.code !== 50433) {
console.error(e);
response.setStatusCode(500);
response.setBody({
error: {
message: 'error creating conversation participant',
explanation: 'Something went wrong when creating a conversation participant.',
},
});
return callback(null, response);
}
}
}
// Create token
const token = new AccessToken(ACCOUNT_SID, TWILIO_API_KEY_SID, TWILIO_API_KEY_SECRET, {
ttl: MAX_ALLOWED_SESSION_DURATION,
});
// Add participant's identity to token
token.identity = user_identity;
// Add video grant to token
const videoGrant = new VideoGrant({ room: stream_name });
token.addGrant(videoGrant);
// Add chat grant to token
if (DISABLE_CHAT !== 'true') {
const chatGrant = new ChatGrant({ serviceSid: CONVERSATIONS_SERVICE_SID });
token.addGrant(chatGrant);
}
// Add sync grant to token
const syncGrant = new SyncGrant({ serviceSid: streamSyncService.sid });
token.addGrant(syncGrant);
// Return token
response.setStatusCode(200);
response.setBody({
token: token.toJwt(),
sync_object_names: {
speakers_map: 'speakers',
viewers_map: 'viewers',
raised_hands_map: `raised_hands`,
},
room_sid: room.sid,
chat_enabled: DISABLE_CHAT !== 'true',
});
return callback(null, response);
};