-
Notifications
You must be signed in to change notification settings - Fork 11
/
app.js
67 lines (59 loc) · 1.83 KB
/
app.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
// ***
// *** Required modules, Listed in the order of importance
// ***
var OpenTokLibrary = require('opentok');
var express = require('express');
// ***
// *** OpenTok Constants for creating Session and Token values
// ***
var OTKEY = process.env.TB_KEY;
var OTSECRET = process.env.TB_SECRET;
// ***
// *** Setup when server first starts
// ***
var urlSessions = {};
var OpenTokObject = new OpenTokLibrary.OpenTokSDK(OTKEY, OTSECRET);
// ***
// *** Setup Express to handle static files in public folder
// *** Express is also great for handling url routing
// ***
var app = express();
app.use(express.static(__dirname + '/public'));
app.set( 'views', __dirname + "/views");
app.set( 'view engine', 'ejs' );
// ***
// *** When user goes to root directory, redirect them to a room (timestamp)
// ***
app.get("/", function( req, res ){
res.writeHead(302, { 'Location': Date.now() });
res.end();
});
// ***
// *** When user goes to root directory, redirect them to a room (timestamp)
// *** If sessionId does not exist for url, create one
// ***
app.get("/:room", function(req, res){
if(urlSessions[ req.params.room ] == undefined){
OpenTokObject.createSession(function(err, sessionId){
urlSessions[ req.params.room ] = sessionId;
sendResponse( sessionId, res );
});
}else{
sessionId = urlSessions[req.params.room];
sendResponse( sessionId, res );
}
});
// ***
// *** start server, listen to port (predefined or 9393)
// ***
var port = process.env.PORT || 9393;
app.listen(port);
// ***
// *** All sessionIds need a corresponding token
// *** generateToken and then sendResponse based on ejs template
// ***
function sendResponse( sessionId, responder ){
var token = OpenTokObject.generateToken( {session_id: sessionId} );
var data = {OpenTokKey:OTKEY, sessionId: sessionId, token:token};
responder.render( 'index', data );
}