openvidu-js-node update to 2.0.0

This commit is contained in:
pabloFuente 2018-05-10 10:33:41 +02:00
parent 7324730bed
commit 03c8036cc3
6 changed files with 10464 additions and 15332 deletions

View File

@ -17,9 +17,9 @@
},
"homepage": "https://github.com/OpenVidu/openvidu-tutorials#readme",
"dependencies": {
"body-parser": "^1.17.2",
"express": "^4.15.3",
"express-session": "^1.15.3",
"openvidu-node-client": "1.7.0"
"body-parser": "1.18.2",
"express": "4.16.3",
"express-session": "1.15.6",
"openvidu-node-client": "2.0.0"
}
}

View File

@ -1,75 +1,84 @@
var OV;
var session;
var sessionId;
var token;
var nickName;
var userName;
var sessionName;
var sessionName; // Name of the video session the user will connect to
var token; // Token retrieved from OpenVidu Server
/* OPENVIDU METHODS */
function joinSession() {
getSessionIdAndToken(function () {
getToken((token) => {
// --- 1) Get an OpenVidu object and init a session with the retrieved sessionId ---
// --- 1) Get an OpenVidu object ---
OV = new OpenVidu();
session = OV.initSession(sessionId);
// --- 2) Init a session ---
// --- 2) Specify the actions when events take place ---
session = OV.initSession();
// --- 3) Specify the actions when events take place in the session ---
// On every new Stream received...
session.on('streamCreated', function (event) {
session.on('streamCreated', (event) => {
// Subscribe to the Stream to receive it
// HTML video will be appended to element with 'video-container' id
var subscriber = session.subscribe(event.stream, 'video-container');
// When the HTML video has been appended to DOM...
subscriber.on('videoElementCreated', function (event) {
// Add a new <p> element for the user's name and nickname just below its video
subscriber.on('videoElementCreated', (event) => {
// Add a new HTML element for the user's name and nickname over its video
appendUserData(event.element, subscriber.stream.connection);
});
});
// On every Stream destroyed...
session.on('streamDestroyed', function (event) {
session.on('streamDestroyed', (event) => {
// Delete the HTML element with the user's name and nickname
removeUserData(event.stream.connection);
});
// --- 4) Connect to the session passing the retrieved token and some more data from
// the client (in this case a JSON with the nickname chosen by the user) ---
var nickName = $("#nickName").val();
session.connect(token, { clientData: nickName })
.then(() => {
// --- 3) Connect to the session passing the retrieved token and some more data from
// the client (in this case a JSON with the nickname chosen by the user) ---
// --- 5) Set page layout for active call ---
session.connect(token, '{"clientData": "' + nickName + '"}', function (error) {
var userName = $("#user").val();
$('#session-title').text(sessionName);
$('#join').hide();
$('#session').show();
// If the connection is successful, initialize a publisher and publish to the session
if (!error) {
// Here we check somehow if the user has at least 'PUBLISHER' role before
// Here we check somehow if the user has 'PUBLISHER' role before
// trying to publish its stream. Even if someone modified the client's code and
// published the stream, it wouldn't work if the token sent in Session.connect
// method doesn't belong to a 'PUBLIHSER' role
if (isPublisher()) {
// method is not recognized as 'PUBLIHSER' role by OpenVidu Server
if (isPublisher(userName)) {
// --- 4) Get your own camera stream ---
// --- 6) Get your own camera stream ---
var publisher = OV.initPublisher('video-container', {
audio: true, // Whether you want to transmit audio or not
video: true, // Whether you want to transmit video or not
audioActive: true, // Whether you want to start the publishing with your audio unmuted or muted
videoActive: true, // Whether you want to start the publishing with your video enabled or disabled
quality: 'MEDIUM', // The quality of your video ('LOW', 'MEDIUM', 'HIGH')
screen: false // true to get your screen as video source instead of your camera
audioSource: undefined, // The source of audio. If undefined default microphone
videoSource: undefined, // The source of video. If undefined default webcam
publishAudio: true, // Whether you want to start publishing with your audio unmuted or not
publishVideo: true, // Whether you want to start publishing with your video enabled or not
resolution: '640x480', // The resolution of your video
frameRate: 30, // The frame rate of your video
insertMode: 'APPEND', // How the video is inserted in the target element 'video-container'
mirror: false // Whether to mirror your local video or not
});
// --- 7) Specify the actions when events take place in our publisher ---
// When our HTML video has been added to DOM...
publisher.on('videoElementCreated', function (event) {
publisher.on('videoElementCreated', (event) => {
// Init the main video with ours and append our data
var userData = {
nickName: nickName,
@ -77,11 +86,11 @@ function joinSession() {
};
initMainVideo(event.element, userData);
appendUserData(event.element, userData);
$(event.element).prop('muted', true); // Mute lcoal video
$(event.element).prop('muted', true); // Mute local video
});
// --- 5) Publish your stream ---
// --- 8) Publish your stream ---
session.publish(publisher);
@ -89,22 +98,18 @@ function joinSession() {
console.warn('You don\'t have permissions to publish');
initMainVideoThumbnail(); // Show SUBSCRIBER message in main video
}
} else {
})
.catch(error => {
console.warn('There was an error connecting to the session:', error.code, error.message);
}
});
$('#session-title').text(sessionName);
$('#join').hide();
$('#session').show();
return false;
});
});
return false;
}
function leaveSession() {
// 6) Leave the session by calling 'disconnect' method over the Session object
// --- 9) Leave the session by calling 'disconnect' method over the Session object ---
session.disconnect();
session = null;
@ -125,67 +130,66 @@ function leaveSession() {
function logIn() {
var user = $("#user").val(); // Username
var pass = $("#pass").val(); // Password
var jsonBody = JSON.stringify({ // Body of POST request
'user': user,
'pass': pass
});
userName = user;
httpRequest('POST', '/api-login/login', jsonBody, 'Login WRONG', function successCallback(response){ // Send POST request
console.warn(userName + ' login');
$("#name-user").text(user);
$("#not-logged").hide();
$("#logged").show();
// Random nickName and session
$("#sessionName").val("Session " + Math.floor(Math.random() * 10));
$("#participantName").val("Participant " + Math.floor(Math.random() * 100));
});
httpPostRequest(
'api-login/login',
{user: user, pass: pass},
'Login WRONG',
(response) => {
$("#name-user").text(user);
$("#not-logged").hide();
$("#logged").show();
// Random nickName and session
$("#sessionName").val("Session " + Math.floor(Math.random() * 10));
$("#nickName").val("Participant " + Math.floor(Math.random() * 100));
}
);
}
function logOut() {
httpRequest('GET', 'api-login/logout', null, 'Logout WRONG', function successCallback(response) {
console.warn(userName + ' logout');
$("#not-logged").show();
$("#logged").hide();
});
httpPostRequest(
'api-login/logout',
{},
'Logout WRONG',
(response) => {
$("#not-logged").show();
$("#logged").hide();
}
);
}
function getSessionIdAndToken(callback) {
function getToken(callback) {
sessionName = $("#sessionName").val(); // Video-call chosen by the user
nickName = $("#participantName").val(); // Nickname chosen by the user
var jsonBody = JSON.stringify({ // Body of POST request
'session': sessionName
});
// Send POST request
httpRequest('POST', 'api-sessions/get-sessionid-token', jsonBody, 'Request of SESSIONID and TOKEN gone WRONG:', function successCallback(response) {
sessionId = response[0]; // Get sessionId from response
token = response[1]; // Get token from response
console.warn('Request of SESSIONID and TOKEN gone WELL (SESSIONID:' + sessionId + ", TOKEN:" + token + ")");
callback(); // Continue the join operation
});
httpPostRequest(
'api-sessions/get-token',
{sessionName: sessionName},
'Request of TOKEN gone WRONG:',
(response) => {
token = response[0]; // Get token from response
console.warn('Request of TOKEN gone WELL (TOKEN:' + token + ')');
callback(token); // Continue the join operation
}
);
}
function removeUser() {
// Body of POST request with the name of the session and the token of the leaving user
var jsonBody = JSON.stringify({
'sessionName': sessionName,
'token': token
});
// Send POST request
httpRequest('POST', 'api-sessions/remove-user', jsonBody, 'User couldn\'t be removed from session', function successCallback(response) {
console.warn(userName + " correctly removed from session");
});
httpPostRequest(
'api-sessions/remove-user',
{sessionName: sessionName, token: token},
'User couldn\'t be removed from session',
(response) => {
console.warn("You have been removed from session " + sessionName);
}
);
}
function httpRequest(method, url, body, errorMsg, callback) {
function httpPostRequest(url, body, errorMsg, callback) {
var http = new XMLHttpRequest();
http.open(method, url, true);
http.open('POST', url, true);
http.setRequestHeader('Content-type', 'application/json');
http.addEventListener('readystatechange', processRequest, false);
http.send(body);
http.send(JSON.stringify(body));
function processRequest() {
if (http.readyState == 4) {
@ -209,7 +213,7 @@ function httpRequest(method, url, body, errorMsg, callback) {
/* APPLICATION BROWSER METHODS */
window.onbeforeunload = function () { // Gracefully leave session
window.onbeforeunload = () => { // Gracefully leave session
if (session) {
removeUser();
leaveSession();
@ -261,9 +265,12 @@ function addClickListener(videoElement, clientData, serverData) {
videoElement.addEventListener('click', function () {
var mainVideo = $('#main-video video').get(0);
if (mainVideo.srcObject !== videoElement.srcObject) {
$('#main-video p.nickName').html(clientData);
$('#main-video p.userName').html(serverData);
mainVideo.srcObject = videoElement.srcObject;
$('#main-video').fadeOut("fast", () => {
$('#main-video p.nickName').html(clientData);
$('#main-video p.userName').html(serverData);
mainVideo.srcObject = videoElement.srcObject;
$('#main-video').fadeIn("fast");
});
}
});
}
@ -279,7 +286,7 @@ function initMainVideoThumbnail() {
$('#main-video video').css("background", "url('images/subscriber-msg.jpg') round");
}
function isPublisher() {
function isPublisher(userName) {
return userName.includes('publisher');
}

View File

@ -7,17 +7,14 @@
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon">
<!-- Bootstrap -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha256-k2WSCIexGzOj3Euiig+TlR8gA0EmPjuc79OEeY5L45g="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Bootstrap -->
<link rel="styleSheet" href="style.css" type="text/css" media="screen">
<script src="openvidu-browser-1.8.0.js"></script>
<script src="openvidu-browser-2.0.0.js"></script>
<script src="app.js"></script>
<script>
$(document).ready(function () {
@ -88,7 +85,7 @@
<form class="form-group" onsubmit="return false">
<p>
<label>Participant</label>
<input class="form-control" type="text" id="participantName" required>
<input class="form-control" type="text" id="nickName" required>
</p>
<p>
<label>Session</label>

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -63,13 +63,13 @@ var OPENVIDU_URL = process.argv[2];
// Environment variable: secret shared with our OpenVidu server
var OPENVIDU_SECRET = process.argv[3];
// OpenVidu object to ask openvidu-server for sessionId and token
// Entrypoint to OpenVidu Node Client SDK
var OV = new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET);
// Collection to pair session names and OpenVidu Session objects
var mapSessionNameSession = {};
// Collection to pair sessionId's (identifiers of Session objects) and tokens
var mapSessionIdTokens = {};
// Collection to pair session names with OpenVidu Session objects
var mapSessions = {};
// Collection to pair session names with tokens
var mapSessionNamesTokens = {};
console.log("App listening on port 5000");
@ -81,7 +81,7 @@ console.log("App listening on port 5000");
// Login
app.post('/api-login/login', function (req, res) {
// Retrieve params from POST body
var user = req.body.user;
var pass = req.body.pass;
@ -102,91 +102,89 @@ app.post('/api-login/login', function (req, res) {
});
// Logout
app.get('/api-login/logout', function (req, res) {
app.post('/api-login/logout', function (req, res) {
console.log("'" + req.session.loggedUser + "' has logged out");
req.session.destroy();
res.status(200).send();
});
// Get sessionId and token (add new user to session)
app.post('/api-sessions/get-sessionid-token', function (req, res) {
// Get token (add new user to session)
app.post('/api-sessions/get-token', function (req, res) {
if (!isLogged(req.session)) {
req.session.destroy();
res.status(401).send('User not logged');
} else {
// The video-call to connect ("TUTORIAL")
var sessionName = req.body.session;
// The video-call to connect
var sessionName = req.body.sessionName;
// Role associated to this user
var role = users.find(u => (u.user === req.session.loggedUser)).role;
// Optional data to be passed to other users when this user connects to the video-call
// In this case, a JSON with the value we stored in the req.session object on login
var serverData = '{"serverData": "' + req.session.loggedUser + '"}';
var serverData = JSON.stringify({ serverData: req.session.loggedUser });
console.log("Getting a token | {sessionName}={" + sessionName + "}");
console.log("Getting sessionId and token | {sessionName}={" + sessionName + "}");
// Build tokenOptions object with the serverData and the role
var tokenOptions = new TokenOptions.Builder()
.data(serverData)
.role(role)
.build();
var tokenOptions = {
data: serverData,
role: role
};
if (mapSessionNameSession[sessionName]) {
// Session already exists: return existing sessionId and a new token
if (mapSessions[sessionName]) {
// Session already exists
console.log('Existing session ' + sessionName);
// Get the existing Session from the collection
var mySession = mapSessionNameSession[sessionName];
var mySession = mapSessions[sessionName];
// Generate a new token asynchronously with the recently created tokenOptions
mySession.generateToken(tokenOptions, function (token) {
// Get the existing sessionId
mySession.getSessionId(function (sessionId) {
mySession.generateToken(tokenOptions)
.then(token => {
// Store the new token in the collection of tokens
mapSessionIdTokens[sessionId].push(token);
// Return the sessionId and token to the client
console.log('SESSIONID: ' + sessionId);
console.log('TOKEN: ' + token);
mapSessionNamesTokens[sessionName].push(token);
// Return the token to the client
res.status(200).send({
0: sessionId,
1: token
0: token
});
})
.catch(error => {
console.error(error);
});
});
} else { // New session: return a new sessionId and a new token
} else {
// New session
console.log('New session ' + sessionName);
// Create a new OpenVidu Session
var mySession = OV.createSession();
// Get the sessionId asynchronously
mySession.getSessionId(function (sessionId) {
// Store the new Session in the collection of Sessions
mapSessionNameSession[sessionName] = mySession;
// Store a new empty array in the collection of tokens
mapSessionIdTokens[sessionId] = [];
// Generate a new token asynchronously with the recently created tokenOptions
mySession.generateToken(tokenOptions, function (token) {
// Store the new token in the collection of tokens
mapSessionIdTokens[sessionId].push(token);
// Create a new OpenVidu Session asynchronously
OV.createSession()
.then(session => {
// Store the new Session in the collection of Sessions
mapSessions[sessionName] = session;
// Store a new empty array in the collection of tokens
mapSessionNamesTokens[sessionName] = [];
console.log('SESSIONID: ' + sessionId);
console.log('TOKEN: ' + token);
// Return the sessionId and token to the client
res.status(200).send({
0: sessionId,
1: token
});
// Generate a new token asynchronously with the recently created tokenOptions
session.generateToken(tokenOptions)
.then(token => {
// Store the new token in the collection of tokens
mapSessionNamesTokens[sessionName].push(token);
// Return the Token to the client
res.status(200).send({
0: token
});
})
.catch(error => {
console.error(error);
});
})
.catch(error => {
console.error(error);
});
});
}
}
});
@ -203,35 +201,26 @@ app.post('/api-sessions/remove-user', function (req, res) {
console.log('Removing user | {sessionName, token}={' + sessionName + ', ' + token + '}');
// If the session exists
var mySession = mapSessionNameSession[sessionName];
if (mySession) {
mySession.getSessionId(function (sessionId) {
var tokens = mapSessionIdTokens[sessionId];
if (tokens) {
var index = tokens.indexOf(token);
// If the token exists
if (index !== -1) {
// Token removed!
tokens.splice(index, 1);
console.log(sessionName + ': ' + mapSessionIdTokens[sessionId].toString());
} else {
var msg = 'Problems in the app server: the TOKEN wasn\'t valid';
console.log(msg);
res.status(500).send(msg);
}
if (mapSessionIdTokens[sessionId].length == 0) {
// Last user left: session must be removed
console.log(sessionName + ' empty!');
delete mapSessionNameSession[sessionName];
}
res.status(200).send();
} else {
var msg = 'Problems in the app server: the SESSIONID wasn\'t valid';
console.log(msg);
res.status(500).send(msg);
}
});
if (mapSessions[sessionName] && mapSessionNamesTokens[sessionName]) {
var tokens = mapSessionNamesTokens[sessionName];
var index = tokens.indexOf(token);
// If the token exists
if (index !== -1) {
// Token removed
tokens.splice(index, 1);
console.log(sessionName + ': ' + tokens.toString());
} else {
var msg = 'Problems in the app server: the TOKEN wasn\'t valid';
console.log(msg);
res.status(500).send(msg);
}
if (tokens.length == 0) {
// Last user left: session must be removed
console.log(sessionName + ' empty!');
delete mapSessions[sessionName];
}
res.status(200).send();
} else {
var msg = 'Problems in the app server: the SESSION does not exist';
console.log(msg);