openvidu-recording-node update to 2.0.0

This commit is contained in:
pabloFuente 2018-05-10 13:18:30 +02:00
parent 5e10361484
commit 06cb200625
6 changed files with 10491 additions and 15323 deletions

View File

@ -17,9 +17,8 @@
},
"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.8.0"
"body-parser": "1.18.2",
"express": "4.16.3",
"openvidu-node-client": "2.0.0"
}
}

View File

@ -1,88 +1,94 @@
var OV;
var session;
var sessionId;
var token;
var sessionName;
var token;
var numVideos = 0;
/* OPENVIDU METHODS */
function joinSession() {
getSessionIdAndToken(function () {
getToken(function () {
// --- 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) {
subscriber.on('videoElementCreated', (event) => {
// Add a new HTML element for the user's name and nickname over its video
updateNumVideos(1);
});
// When the HTML video has been appended to DOM...
subscriber.on('videoElementDestroyed', function (event) {
subscriber.on('videoElementDestroyed', (event) => {
// Add a new HTML element for the user's name and nickname over its video
updateNumVideos(-1);
});
});
// --- 3) Connect to the session passing the retrieved token ---
// --- 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) ---
session.connect(token, null, function (error) {
session.connect(token)
.then(() => {
// If the connection is successful, initialize a publisher and publish to the session
if (!error) {
// --- 5) Set page layout for active call ---
// --- 4) Get your own camera stream ---
$('#session-title').text(sessionName);
$('#join').hide();
$('#session').show();
// --- 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) => {
updateNumVideos(1);
$(event.element).prop('muted', true); // Mute local video
});
// When the HTML video has been appended to DOM...
publisher.on('videoElementDestroyed', function (event) {
publisher.on('videoElementDestroyed', (event) => {
// Add a new HTML element for the user's name and nickname over its video
updateNumVideos(-1);
});
// --- 5) Publish your stream ---
// --- 8) Publish your stream ---
session.publish(publisher);
} 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;
});
@ -90,12 +96,12 @@ function joinSession() {
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;
numVideos = 0;
$('#join').show();
$('#session').hide();
}
@ -106,33 +112,32 @@ function leaveSession() {
/* APPLICATION REST METHODS */
function getSessionIdAndToken(callback) {
function getToken(callback) {
sessionName = $("#sessionName").val(); // Video-call chosen by the user
var jsonBody = JSON.stringify({ // Body of POST request
'session': sessionName
});
// Send POST request
httpRequest('POST', 'api/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
});
httpRequest(
'POST',
'api/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/remove-user', jsonBody, 'User couldn\'t be removed from session', function successCallback(response) {
console.warn("User correctly removed from session");
});
httpRequest(
'POST',
'api/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) {
@ -141,7 +146,7 @@ function httpRequest(method, url, body, errorMsg, callback) {
http.open(method, 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) {
@ -163,48 +168,69 @@ function httpRequest(method, url, body, errorMsg, callback) {
var recordingId;
function startRecording() {
var jsonBody = JSON.stringify({
'session': session.sessionId
});
httpRequest('POST', 'api/recording/start', jsonBody, 'Start recording WRONG', function successCallback(response) {
console.log(response);
recordingId = response.id;
$('#text-area').text(JSON.stringify(response, null, "\t"));
});
httpRequest(
'POST',
'api/recording/start',
{session: session.sessionId},
'Start recording WRONG',
(response) => {
console.log(response);
recordingId = response.id;
$('#text-area').text(JSON.stringify(response, null, "\t"));
}
);
}
function stopRecording() {
var jsonBody = JSON.stringify({
'recording': recordingId
});
httpRequest('POST', 'api/recording/stop', jsonBody, 'Stop recording WRONG', function successCallback(response) {
console.log(response);
$('#text-area').text(JSON.stringify(response, null, "\t"));
});
httpRequest(
'POST',
'api/recording/stop',
{recording: recordingId},
'Stop recording WRONG',
(response) => {
console.log(response);
$('#text-area').text(JSON.stringify(response, null, "\t"));
}
);
}
function deleteRecording() {
var jsonBody = JSON.stringify({
'recording': recordingId
});
httpRequest('DELETE', 'api/recording/delete', jsonBody, 'Delete recording WRONG', function successCallback() {
console.log("DELETE ok");
$('#text-area').text("DELETE ok");
});
httpRequest(
'DELETE',
'api/recording/delete',
{recording: recordingId},
'Delete recording WRONG',
() => {
console.log("DELETE ok");
$('#text-area').text("DELETE ok");
}
);
}
function getRecording() {
httpRequest('GET', 'api/recording/get/' + recordingId, '', 'Get recording WRONG', function successCallback(response) {
console.log(response);
$('#text-area').text(JSON.stringify(response, null, "\t"));
});
httpRequest(
'GET',
'api/recording/get/' + recordingId,
{},
'Get recording WRONG',
(response) => {
console.log(response);
$('#text-area').text(JSON.stringify(response, null, "\t"));
}
);
}
function listRecordings() {
httpRequest('GET', 'api/recording/list', '', 'List recordings WRONG', function successCallback(response) {
console.log(response);
$('#text-area').text(JSON.stringify(response, null, "\t"));
});
httpRequest(
'GET',
'api/recording/list',
{},
'List recordings WRONG',
(response) => {
console.log(response);
$('#text-area').text(JSON.stringify(response, null, "\t"));
}
);
}
/* APPLICATION REST METHODS */

View File

@ -17,7 +17,7 @@
<!-- 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 () {

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View File

@ -16,17 +16,11 @@ process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"
// Node imports
var express = require('express');
var fs = require('fs');
var session = require('express-session');
var https = require('https');
var bodyParser = require('body-parser'); // Pull information from HTML POST (express4)
var app = express(); // Create our app with express
// Server configuration
app.use(session({
saveUninitialized: true,
resave: false,
secret: 'MY_SECRET'
}));
app.use(express.static(__dirname + '/public')); // Set the static files location
app.use(bodyParser.urlencoded({
'extended': 'true'
@ -48,13 +42,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");
@ -63,76 +57,72 @@ console.log("App listening on port 5000");
/* Session API */
// Get sessionId and token (add new user to session)
app.post('/api/get-sessionid-token', function (req, res) {
// The video-call to connect ("TUTORIAL")
var sessionName = req.body.session;
console.log("Getting sessionId and token | {sessionName}={" + sessionName + "}");
// Get token (add new user to session)
app.post('/api/get-token', function (req, res) {
// The video-call to connect
var sessionName = req.body.sessionName;
// Role associated to this user
var role = OpenViduRole.PUBLISHER;
// Build tokenOptions object with the serverData and the role
var tokenOptions = new TokenOptions.Builder()
.role(role)
.build();
console.log("Getting a token | {sessionName}={" + sessionName + "}");
if (mapSessionNameSession[sessionName]) {
// Session already exists: return existing sessionId and a new token
// Build tokenOptions object with PUBLIHSER role
var tokenOptions = { role: role }
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);
mapSessionNamesTokens[sessionName].push(token);
// Return the sessionId and token to the client
console.log('SESSIONID: ' + sessionId);
console.log('TOKEN: ' + 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();
// 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] = [];
// Get the sessionId asynchronously
mySession.getSessionId(function (sessionId) {
// Generate a new token asynchronously with the recently created tokenOptions
session.generateToken(tokenOptions)
.then(token => {
// Store the new Session in the collection of Sessions
mapSessionNameSession[sessionName] = mySession;
// Store a new empty array in the collection of tokens
mapSessionIdTokens[sessionId] = [];
// Store the new token in the collection of tokens
mapSessionNamesTokens[sessionName].push(token);
// 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);
console.log('SESSIONID: ' + sessionId);
console.log('TOKEN: ' + token);
// Return the sessionId and token to the client
res.status(200).send({
0: sessionId,
1: token
});
// Return the Token to the client
res.status(200).send({
0: token
});
})
.catch(error => {
console.error(error);
});
})
.catch(error => {
console.error(error);
});
});
}
});
@ -143,36 +133,27 @@ app.post('/api/remove-user', function (req, res) {
var token = req.body.token;
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 session exists
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 + ': ' + 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 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);
@ -182,32 +163,31 @@ app.post('/api/remove-user', function (req, res) {
/* Recording API */
// Start session recording
// Start recording
app.post('/api/recording/start', function (req, res) {
// Retrieve params from POST body
var sessionId = req.body.session;
console.log("Starting recording | {sessionId}=" + sessionId);
OV.startRecording(sessionId)
.then(archive => res.status(200).send(archive))
.then(recording => res.status(200).send(getJsonFromRecording(recording)))
.catch(error => res.status(400).send(error.message));
});
// Start session recording
// Stop recording
app.post('/api/recording/stop', function (req, res) {
// Retrieve params from POST body
var recordingId = req.body.recording;
console.log("Stoping recording | {recordingId}=" + recordingId);
OV.stopRecording(recordingId)
.then(archive => res.status(200).send(archive))
.then(recording => res.status(200).send(getJsonFromRecording(recording)))
.catch(error => res.status(400).send(error.message));
});
// Start session recording
// Delete recording
app.delete('/api/recording/delete', function (req, res) {
// Retrieve params from DELETE body
var recordingId = req.body.recording;
@ -218,22 +198,46 @@ app.delete('/api/recording/delete', function (req, res) {
.catch(error => res.status(400).send(error.message));
});
// Start session recording
// Get recording
app.get('/api/recording/get/:recordingId', function (req, res) {
// Retrieve params from GET url
var recordingId = req.params.recordingId;
console.log("Getting recording | {recordingId}=" + recordingId);
OV.getRecording(recordingId)
.then(archive => res.status(200).send(archive))
.then(recording => res.status(200).send(getJsonFromRecording(recording)))
.catch(error => res.status(400).send(error.message));
});
// Start session recording
// List all recordings
app.get('/api/recording/list', function (req, res) {
console.log("Listing recordings");
OV.listRecordings()
.then(archives => res.status(200).send(archives))
.then(recordings => res.status(200).send(getJsonArrayFromRecordingList(recordings)))
.catch(error => res.status(400).send(error.message));
});
});
function getJsonFromRecording(recording) {
return {
"createdAt": recording.createdAt,
"duration": recording.duration,
"hasAudio": recording.hasAudio,
"hasVideo": recording.hasVideo,
"id": recording.id,
"name": recording.name,
"recordingLayout": recording.recordingLayout,
"sessionId": recording.sessionId,
"size": recording.size,
"status": recording.status,
"url": recording.url
}
}
function getJsonArrayFromRecordingList(recordings) {
var jsonArray = [];
recordings.forEach(recording => {
jsonArray.push(getJsonFromRecording(recording));
})
return jsonArray;
}