Migrated openvidu-roles-node to Livekit

This commit is contained in:
Carlos Santos 2023-11-03 11:38:22 +01:00
parent 15b49adbc3
commit 619596ff43
7 changed files with 1191 additions and 14877 deletions

File diff suppressed because it is too large Load Diff

View File

@ -10,16 +10,17 @@
"type": "git",
"url": "git+https://github.com/OpenVidu/openvidu-tutorials.git"
},
"author": "openvidu@gmail.com",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/OpenVidu/openvidu-tutorials/issues"
},
"homepage": "https://github.com/OpenVidu/openvidu-tutorials#readme",
"dependencies": {
"body-parser": "1.19.0",
"express": "4.17.1",
"express-session": "1.17.1",
"openvidu-node-client": "2.27.0"
"body-parser": "1.20.2",
"cors": "2.8.5",
"dotenv": "^16.3.1",
"express": "4.18.2",
"express-session": "1.17.3",
"livekit-server-sdk": "1.2.7"
}
}

View File

@ -1,115 +1,84 @@
var OV;
var session;
var sessionName; // Name of the video session the user will connect to
var token; // Token retrieved from OpenVidu Server
var LivekitClient = window.LivekitClient;
var room;
var myRoomName;
var token;
var nickname;
/* OPENVIDU METHODS */
function joinSession() {
function joinRoom() {
document.getElementById('join-btn').disabled = true;
document.getElementById('join-btn').innerHTML = 'Joining...';
const myParticipantName = $('#myParticipantName').val();
const myRoomName = $('#myRoomName').val();
document.getElementById("join-btn").disabled = true;
document.getElementById("join-btn").innerHTML = "Joining...";
room = new LivekitClient.Room();
getToken((token) => {
room.on(
LivekitClient.RoomEvent.TrackSubscribed,
(track, publication, participant) => {
const element = track.attach();
element.id = track.sid;
element.className = 'removable';
document.getElementById('video-container').appendChild(element);
if (track.kind === 'video') {
var participantNickname;
try {
participantNickname = JSON.parse(participant.metadata).nickname;
} catch (error) {
console.warn('Error parsing participant metadata: ' + error);
}
appendUserData(element, participant.identity, participantNickname);
}
}
);
// --- 1) Get an OpenVidu object ---
// On every new Track destroyed...
room.on(
LivekitClient.RoomEvent.TrackUnsubscribed,
(track, publication, participant) => {
track.detach();
document.getElementById(track.sid)?.remove();
if (track.kind === 'video') {
removeUserData(participant);
}
}
);
OV = new OpenVidu();
getToken(myRoomName, myParticipantName).then((token) => {
const livekitUrl = getLivekitUrlFromMetadata(token);
// --- 2) Init a session ---
session = OV.initSession();
// --- 3) Specify the actions when events take place in the session ---
// On every new Stream received...
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', (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', (event) => {
// Delete the HTML element with the user's name and nickname
removeUserData(event.stream.connection);
});
// On every asynchronous exception...
session.on('exception', (exception) => {
console.warn(exception);
});
// --- 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(() => {
// --- 5) Set page layout for active call ---
var userName = $("#user").val();
$('#session-title').text(sessionName);
room
.connect(livekitUrl, token)
.then(async () => {
var participantName = $('#user').val();
$('#room-title').text(myRoomName);
$('#join').hide();
$('#session').show();
$('#room').show();
const canPublish = room.localParticipant.permissions.canPublish;
// 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 is not recognized as 'PUBLIHSER' role by OpenVidu Server
if (isPublisher(userName)) {
// --- 6) Get your own camera stream ---
var publisher = OV.initPublisher('video-container', {
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', (event) => {
// Init the main video with ours and append our data
var userData = {
nickName: nickName,
userName: userName
};
initMainVideo(event.element, userData);
appendUserData(event.element, userData);
$(event.element).prop('muted', true); // Mute local video
});
// --- 8) Publish your stream ---
session.publish(publisher);
if (canPublish) {
const [microphonePublication, cameraPublication] = await Promise.all([
room.localParticipant.setMicrophoneEnabled(true),
room.localParticipant.setCameraEnabled(true),
]);
const element = cameraPublication.track.attach();
element.className = 'removable';
document.getElementById('video-container').appendChild(element);
initMainVideo(element, myParticipantName, nickname);
appendUserData(element, myParticipantName, nickname);
} else {
console.warn('You don\'t have permissions to publish');
initMainVideoThumbnail(); // Show SUBSCRIBER message in main video
initMainVideoThumbnail();
}
})
.catch(error => {
console.warn('There was an error connecting to the session:', error.code, error.message);
.catch((error) => {
console.warn(
'There was an error connecting to the room:',
error.code,
error.message
);
enableBtn();
});
});
@ -117,159 +86,149 @@ function joinSession() {
return false;
}
function leaveSession() {
// --- 9) Leave the session by calling 'disconnect' method over the Session object ---
session.disconnect();
session = null;
function leaveRoom() {
room.disconnect();
room = null;
// Removing all HTML elements with the user's nicknames
cleanSessionView();
cleanRoomView();
$('#join').show();
$('#session').hide();
$('#room').hide();
// eneble button
enableBtn();
}
/* OPENVIDU METHODS */
function enableBtn (){
document.getElementById("join-btn").disabled = false;
document.getElementById("join-btn").innerHTML = "Join!";
function enableBtn() {
document.getElementById('join-btn').disabled = false;
document.getElementById('join-btn').innerHTML = 'Join!';
}
/* APPLICATION REST METHODS */
function logIn() {
var user = $("#user").val(); // Username
var pass = $("#pass").val(); // Password
nickname = $('#user').val();
var pass = $('#pass').val();
httpPostRequest(
'api-login/login',
{user: user, pass: pass},
'login',
{ user: nickname, 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));
$('#name-user').text(nickname);
$('#not-logged').hide();
$('#logged').show();
// Random myParticipantName and room
$('#myRoomName').val('Room ' + Math.floor(Math.random() * 10));
$('#myParticipantName').val(
'Participant ' + Math.floor(Math.random() * 100)
);
}
);
}
function logOut() {
httpPostRequest(
'api-login/logout',
{},
'Logout WRONG',
(response) => {
$("#not-logged").show();
$("#logged").hide();
}
);
httpPostRequest('logout', {}, 'Logout WRONG', (response) => {
$('#not-logged').show();
$('#logged').hide();
});
enableBtn();
}
function getToken(callback) {
sessionName = $("#sessionName").val(); // Video-call chosen by the user
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 getToken(roomName, participantName) {
return new Promise((resolve, reject) => {
// Video-call chosen by the user
httpPostRequest(
'token',
{ roomName, participantName },
'Error generating token',
(response) => resolve(response.token)
);
});
}
function removeUser() {
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);
}
);
}
async function httpPostRequest(url, body, errorMsg, successCallback) {
try {
const response = await fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(body),
});
function httpPostRequest(url, body, errorMsg, callback) {
var http = new XMLHttpRequest();
http.open('POST', url, true);
http.setRequestHeader('Content-type', 'application/json');
http.addEventListener('readystatechange', processRequest, false);
http.send(JSON.stringify(body));
function processRequest() {
if (http.readyState == 4) {
if (http.status == 200) {
try {
callback(JSON.parse(http.responseText));
} catch (e) {
callback();
}
} else {
console.warn(errorMsg);
console.warn(http.responseText);
}
if (response.ok) {
const data = await response.json();
successCallback(data);
} else {
console.warn(errorMsg);
console.warn('Error: ' + response.statusText);
}
} catch (error) {
console.error(error);
}
}
/* APPLICATION REST METHODS */
/* APPLICATION BROWSER METHODS */
window.onbeforeunload = () => { // Gracefully leave session
if (session) {
removeUser();
leaveSession();
window.onbeforeunload = () => {
if (room) {
leaveRoom();
}
logOut();
};
function getLivekitUrlFromMetadata(token) {
if (!token) throw new Error('Trying to get metadata from an empty token');
try {
const base64Url = token.split('.')[1];
const base64 = base64Url.replace(/-/g, '+').replace(/_/g, '/');
const jsonPayload = decodeURIComponent(
window
.atob(base64)
.split('')
.map((c) => {
return '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2);
})
.join('')
);
const payload = JSON.parse(jsonPayload);
if (!payload?.metadata) throw new Error('Token does not contain metadata');
const metadata = JSON.parse(payload.metadata);
return metadata.livekitUrl;
} catch (error) {
throw new Error('Error decoding and parsing token: ' + error);
}
}
function appendUserData(videoElement, connection) {
var clientData;
var serverData;
var nodeId;
if (connection.nickName) { // Appending local video data
clientData = connection.nickName;
serverData = connection.userName;
nodeId = 'main-videodata';
} else {
clientData = JSON.parse(connection.data.split('%/%')[0]).clientData;
serverData = JSON.parse(connection.data.split('%/%')[1]).serverData;
nodeId = connection.connectionId;
}
function appendUserData(videoElement, participantName, nickname) {
var dataNode = document.createElement('div');
dataNode.className = "data-node";
dataNode.id = "data-" + nodeId;
dataNode.innerHTML = "<p class='nickName'>" + clientData + "</p><p class='userName'>" + serverData + "</p>";
dataNode.className = 'removable';
dataNode.id = 'data-' + participantName;
dataNode.innerHTML = `
<p class='nickname'>${nickname}</p>
<p class='participantName'>${participantName}</p>
`;
videoElement.parentNode.insertBefore(dataNode, videoElement.nextSibling);
addClickListener(videoElement, clientData, serverData);
addClickListener(videoElement, participantName);
}
function removeUserData(connection) {
var userNameRemoved = $("#data-" + connection.connectionId);
if ($(userNameRemoved).find('p.userName').html() === $('#main-video p.userName').html()) {
cleanMainVideo(); // The participant focused in the main video has left
}
$("#data-" + connection.connectionId).remove();
function removeUserData(participant) {
var dataNode = document.getElementById('data-' + participant.identity);
dataNode?.parentNode.removeChild(dataNode);
}
function removeAllUserData() {
$(".data-node").remove();
var elementsToRemove = document.getElementsByClassName('removable');
while (elementsToRemove[0]) {
elementsToRemove[0].parentNode.removeChild(elementsToRemove[0]);
}
}
function cleanMainVideo() {
@ -283,35 +242,33 @@ function addClickListener(videoElement, clientData, serverData) {
videoElement.addEventListener('click', function () {
var mainVideo = $('#main-video video').get(0);
if (mainVideo.srcObject !== videoElement.srcObject) {
$('#main-video').fadeOut("fast", () => {
$('#main-video p.nickName').html(clientData);
$('#main-video p.userName').html(serverData);
$('#main-video').fadeOut('fast', () => {
$('#main-video p.nickname').html(clientData);
$('#main-video p.participantName').html(serverData);
mainVideo.srcObject = videoElement.srcObject;
$('#main-video').fadeIn("fast");
$('#main-video').fadeIn('fast');
});
}
});
}
function initMainVideo(videoElement, userData) {
function initMainVideo(videoElement, participantName, nickname) {
$('#main-video video').get(0).srcObject = videoElement.srcObject;
$('#main-video p.nickName').html(userData.nickName);
$('#main-video p.userName').html(userData.userName);
$('#main-video video').prop('muted', true);
$('#main-video p.nickname').html(nickname);
$('#main-video p.participantName').html(participantName);
}
function initMainVideoThumbnail() {
$('#main-video video').css("background", "url('images/subscriber-msg.jpg') round");
$('#main-video video').css(
'background',
"url('images/subscriber-msg.jpg') round"
);
}
function isPublisher(userName) {
return userName.includes('publisher');
}
function cleanSessionView() {
function cleanRoomView() {
removeAllUserData();
cleanMainVideo();
$('#main-video video').css("background", "");
$('#main-video video').css('background', '');
}
/* APPLICATION BROWSER METHODS */
/* APPLICATION BROWSER METHODS */

View File

@ -1,130 +1,210 @@
<html>
<head>
<title>openvidu-roles-node</title>
<head>
<title>openvidu-roles-node</title>
<meta
name="viewport"
content="width=device-width, initial-scale=1"
charset="utf-8"
/>
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon" />
<meta name="viewport" content="width=device-width, initial-scale=1" charset="utf-8">
<link rel="shortcut icon" href="images/favicon.ico" type="image/x-icon">
<!-- Bootstrap -->
<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 -->
<!-- Bootstrap -->
<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-2.27.0.js"></script>
<script src="app.js"></script>
<script>
$(document).ready(function () {
$('[data-toggle="tooltip"]').tooltip({
html: true
<link rel="styleSheet" href="style.css" type="text/css" media="screen" />
<script src="https://cdn.jsdelivr.net/npm/livekit-client/dist/livekit-client.umd.min.js"></script>
<script src="app.js"></script>
<script>
$(document).ready(function () {
$('[data-toggle="tooltip"]').tooltip({
html: true,
});
});
});
</script>
</head>
</script>
</head>
<body>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/"><img class="demo-logo" src="images/openvidu_vert_white_bg_trans_cropped.png"/> Roles Node</a>
<a class="navbar-brand nav-icon" href="https://github.com/OpenVidu/openvidu-tutorials/tree/master/openvidu-roles-node" title="GitHub Repository"
target="_blank"><i class="fa fa-github" aria-hidden="true"></i></a>
<a class="navbar-brand nav-icon" href="http://www.docs.openvidu.io/en/stable/tutorials/openvidu-roles-node/" title="Documentation" target="_blank"><i class="fa fa-book" aria-hidden="true"></i></a>
<body>
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/"
><img
class="demo-logo"
src="images/openvidu_vert_white_bg_trans_cropped.png"
/>
Roles Node</a
>
<a
class="navbar-brand nav-icon"
href="https://github.com/OpenVidu/openvidu-tutorials/tree/master/openvidu-roles-node"
title="GitHub Repository"
target="_blank"
><i class="fa fa-github" aria-hidden="true"></i
></a>
<a
class="navbar-brand nav-icon"
href="http://www.docs.openvidu.io/en/stable/tutorials/openvidu-roles-node/"
title="Documentation"
target="_blank"
><i class="fa fa-book" aria-hidden="true"></i
></a>
</div>
</div>
</div>
</nav>
</nav>
<div id="main-container" class="container">
<div id="not-logged" class="vertical-center">
<div id="img-div"><img src="images/openvidu_grey_bg_transp_cropped.png" /></div>
<form class="form-group jumbotron" onsubmit="return false">
<p>
<label>User</label><input class="form-control" type="text" id="user" required>
</p>
<p>
<label>Pass</label><input class="form-control" type="password" id="pass" required>
</p>
<p class="text-center">
<button class="btn btn-lg btn-info" onclick="logIn()">Log in</button>
</p>
</form>
<table class="table">
<tr>
<th>User</th>
<th>Pass</th>
<th>Role<i data-toggle="tooltip" data-placement="bottom" title="" data-original-title="<div id='tooltip-div'>PUBLISHER<div>Send and receive media<hr></div>SUBSCRIBER<div>Receive media</div></div>"
class="glyphicon glyphicon-info-sign"></i></th>
</tr>
<tr>
<td>publisher1</td>
<td>pass</td>
<td>PUBLISHER</td>
</tr>
<tr>
<td>publisher2</td>
<td>pass</td>
<td>PUBLISHER</td>
</tr>
<tr>
<td>subscriber</td>
<td>pass</td>
<td>SUBSCRIBER</td>
</tr>
</table>
</div>
<div id="main-container" class="container">
<div id="not-logged" class="vertical-center">
<div id="img-div">
<img src="images/openvidu_grey_bg_transp_cropped.png" />
</div>
<form class="form-group jumbotron" onsubmit="return false">
<p>
<label>User</label
><input class="form-control" type="text" id="user" required />
</p>
<p>
<label>Password</label
><input class="form-control" type="password" id="pass" required />
</p>
<p class="text-center">
<button class="btn btn-lg btn-info" onclick="logIn()">
Log in
</button>
</p>
</form>
<table class="table">
<tr>
<th>User</th>
<th>Password</th>
<th>
Role<i
data-toggle="tooltip"
data-placement="bottom"
title=""
data-original-title="<div id='tooltip-div'>PUBLISHER<div>Send and receive media<hr></div>SUBSCRIBER<div>Receive media</div></div>"
class="glyphicon glyphicon-info-sign"
></i>
</th>
</tr>
<tr>
<td>publisher1</td>
<td>pass</td>
<td>PUBLISHER</td>
</tr>
<tr>
<td>publisher2</td>
<td>pass</td>
<td>PUBLISHER</td>
</tr>
<tr>
<td>subscriber</td>
<td>pass</td>
<td>SUBSCRIBER</td>
</tr>
</table>
</div>
<div id="logged" hidden>
<div id="join" class="vertical-center">
<div id="img-div"><img src="images/openvidu_grey_bg_transp_cropped.png" /></div>
<div id="join-dialog" class="jumbotron">
<h1>Join a video session</h1>
<form class="form-group" onsubmit="return false">
<p>
<label>Participant</label>
<input class="form-control" type="text" id="nickName" required>
</p>
<p>
<label>Session</label>
<input class="form-control" type="text" id="sessionName" required>
</p>
<p class="text-center">
<button class="btn btn-lg btn-success" id="join-btn" onclick="joinSession()">Join!</button>
</p>
</form>
<hr>
<div id="login-info">
<div>Logged as <span id="name-user"></span></div>
<button id="logout-btn" class="btn btn-warning" onclick="logOut()">Log out</button>
<div id="logged" hidden>
<div id="join" class="vertical-center">
<div id="img-div">
<img src="images/openvidu_grey_bg_transp_cropped.png" />
</div>
<div id="join-dialog" class="jumbotron">
<h1>Join a video room</h1>
<form class="form-group" onsubmit="return false">
<p>
<label>Participant</label>
<input
class="form-control"
type="text"
id="myParticipantName"
required
/>
</p>
<p>
<label>Room</label>
<input
class="form-control"
type="text"
id="myRoomName"
required
/>
</p>
<p class="text-center">
<button
class="btn btn-lg btn-success"
id="join-btn"
onclick="joinRoom()"
>
Join!
</button>
</p>
</form>
<hr />
<div id="login-info">
<div>Logged as <span id="name-user"></span></div>
<button
id="logout-btn"
class="btn btn-warning"
onclick="logOut()"
>
Log out
</button>
</div>
</div>
</div>
</div>
<div id="session" style="display: none;">
<div id="session-header">
<h1 id="session-title"></h1>
<input class="btn btn-large btn-danger" type="button" id="buttonLeaveSession" onmouseup="removeUser(); leaveSession()" value="Leave session">
<div id="room" style="display: none">
<div id="room-header">
<h1 id="room-title"></h1>
<input
class="btn btn-large btn-danger"
type="button"
id="buttonLeaveRoom"
onmouseup="leaveRoom()"
value="Leave room"
/>
</div>
<div id="main-video" class="col-md-6">
<p class="nickname"></p>
<p class="participantName"></p>
<video autoplay playsinline="true"></video>
</div>
<div id="video-container" class="col-md-6"></div>
</div>
<div id="main-video" class="col-md-6">
<p class="nickName"></p>
<p class="userName"></p>
<video autoplay playsinline="true"></video>
</div>
<div id="video-container" class="col-md-6"></div>
</div>
</div>
</div>
<footer class="footer">
<div class="container">
<div class="text-muted">OpenVidu © 2022</div>
<a href="http://www.openvidu.io/" target="_blank"><img class="openvidu-logo" src="images/openvidu_globe_bg_transp_cropped.png"/></a>
</div>
</footer>
</body>
<footer class="footer">
<div class="container">
<div class="text-muted">OpenVidu © 2023</div>
<a href="http://www.openvidu.io/" target="_blank"
><img
class="openvidu-logo"
src="images/openvidu_globe_bg_transp_cropped.png"
/></a>
</div>
</footer>
</body>
</html>

File diff suppressed because one or more lines are too long

View File

@ -13,6 +13,10 @@ nav {
border-top-left-radius: 0 !important;
}
.navbar {
margin-bottom: 0px !important;
}
.navbar-header {
width: 100%;
}
@ -41,12 +45,13 @@ nav i.fa:hover {
#main-container {
padding-bottom: 80px;
display: contents;
}
.vertical-center {
width: -webkit-fit-content;
width: fit-content;
margin: auto;
margin: auto;
}
.vertical-center#not-logged form {
@ -215,19 +220,19 @@ a:hover .demo-logo {
margin: auto;
}
#session-header {
#room-header {
margin-bottom: 20px;
}
#session-header form {
#room-header form {
display: inline;
}
#session-title {
#room-title {
display: inline-block;
}
#buttonLeaveSession {
#buttonLeaveRoom {
float: right;
margin-top: 20px;
}
@ -256,7 +261,7 @@ a:hover .demo-logo {
border-bottom-right-radius: 4px;
}
#video-container p.userName {
#video-container p.nickname {
float: right;
border-bottom-left-radius: 4px;
border-bottom-right-radius: 0px;
@ -283,7 +288,7 @@ video {
border-bottom-right-radius: 4px;
}
#main-video p.userName {
#main-video p.nickname {
position: absolute;
right: 0;
font-size: 16px !important;
@ -297,7 +302,7 @@ video {
}
#session img {
#room img {
width: 100%;
height: auto;
display: inline-block;
@ -305,7 +310,7 @@ video {
vertical-align: baseline;
}
#session #video-container img {
#room #video-container img {
position: relative;
float: left;
width: 50%;
@ -351,7 +356,7 @@ table i {
#join {
padding-top: inherit;
}
#not-logged {
padding-top: inherit;
}

View File

@ -1,250 +1,191 @@
/* CONFIGURATION */
var OpenVidu = require('openvidu-node-client').OpenVidu;
var OpenViduRole = require('openvidu-node-client').OpenViduRole;
// For demo purposes we ignore self-signed certificate
process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0"
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
const express = require('express');
const fs = require('fs');
const session = require('express-session');
const https = require('https');
const bodyParser = require('body-parser');
const AccessToken = require('livekit-server-sdk').AccessToken;
const RoomServiceClient = require('livekit-server-sdk').RoomServiceClient;
const cors = require('cors');
const app = express();
// Environment variable: PORT where the node server is listening
var SERVER_PORT = process.env.SERVER_PORT || 5000;
// Environment variable: URL where our OpenVidu server is listening
var OPENVIDU_URL = process.env.OPENVIDU_URL || process.argv[2] || 'http://localhost:4443';
// Environment variable: secret shared with our OpenVidu server
var OPENVIDU_SECRET = process.env.OPENVIDU_SECRET || process.argv[3] || 'MY_SECRET';
// Entrypoint to OpenVidu Node Client SDK
var OV = new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET);
// Collection to pair session names with OpenVidu Session objects
var mapSessions = {};
// Collection to pair session names with tokens
var mapSessionNamesTokens = {};
const SERVER_PORT = process.env.SERVER_PORT || 5000;
// Environment variable: api key shared with our LiveKit deployment
const LIVEKIT_API_KEY = process.env.LIVEKIT_API_KEY || 'devkey';
// Environment variable: api secret shared with our LiveKit deployment
const LIVEKIT_API_SECRET = process.env.LIVEKIT_API_SECRET || 'secret';
// Environment variable: url of our LiveKit deployment
const LIVEKIT_URL = process.env.LIVEKIT_URL || 'ws://localhost:7880';
// Listen (start app with node server.js)
var options = {
key: fs.readFileSync('openvidukey.pem'),
cert: fs.readFileSync('openviducert.pem')
const options = {
key: fs.readFileSync('openvidukey.pem'),
cert: fs.readFileSync('openviducert.pem'),
};
// Mock database
var users = [{
user: "publisher1",
pass: "pass",
role: OpenViduRole.PUBLISHER
}, {
user: "publisher2",
pass: "pass",
role: OpenViduRole.PUBLISHER
}, {
user: "subscriber",
pass: "pass",
role: OpenViduRole.SUBSCRIBER
}];
// The users of our application
// They should be stored in a database
const users = [
{
user: 'publisher1',
pass: 'pass',
role: 'PUBLISHER',
},
{
user: 'publisher2',
pass: 'pass',
role: 'PUBLISHER',
},
{
user: 'subscriber',
pass: 'pass',
role: 'SUBSCRIBER',
},
];
const livekitUrlHostname = LIVEKIT_URL.replace(/^ws:/, 'http:').replace(
/^wss:/,
'https:'
);
// const roomClient = new RoomServiceClient(
// livekitUrlHostname,
// LIVEKIT_API_KEY,
// LIVEKIT_API_SECRET
// );
// Enable CORS support
app.use(
cors({
origin: '*',
})
);
// 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'
})); // Parse application/x-www-form-urlencoded
app.use(bodyParser.json()); // Parse application/json
app.use(bodyParser.json({
type: 'application/vnd.api+json'
})); // Parse application/vnd.api+json as json
app.use(
session({
saveUninitialized: true,
resave: false,
secret: 'MY_SECRET',
})
);
// Set the static files location
app.use(express.static(__dirname + '/public'));
// Parse application/x-www-form-urlencoded
app.use(
bodyParser.urlencoded({
extended: 'true',
})
);
// Parse application/json
app.use(bodyParser.json());
// Parse application/vnd.api+json as json
app.use(
bodyParser.json({
type: 'application/vnd.api+json',
})
);
https.createServer(options, app).listen(SERVER_PORT, () => {
console.log(`App listening on port ${SERVER_PORT}`);
console.log(`OPENVIDU_URL: ${OPENVIDU_URL}`);
console.log(`OPENVIDU_SECRET: ${OPENVIDU_SECRET}`);
console.log(`App listening on port ${SERVER_PORT}`);
console.log(`LIVEKIT API KEY: ${LIVEKIT_API_KEY}`);
console.log(`LIVEKIT API SECRET: ${LIVEKIT_API_SECRET}`);
console.log(`LIVEKIT URL: ${LIVEKIT_URL}`);
console.log();
console.log('Access the app at https://localhost:' + SERVER_PORT);
});
/* CONFIGURATION */
/* REST API */
// Login
app.post('/api-login/login', function (req, res) {
app.post('/login', (req, res) => {
// Retrieve params from body
const { user, pass } = req.body;
// Retrieve params from POST body
var user = req.body.user;
var pass = req.body.pass;
console.log("Logging in | {user, pass}={" + user + ", " + pass + "}");
if (login(user, pass)) { // Correct user-pass
// Validate session and return OK
// Value stored in req.session allows us to identify the user in future requests
console.log("'" + user + "' has logged in");
req.session.loggedUser = user;
res.status(200).send();
} else { // Wrong user-pass
// Invalidate session and return error
console.log("'" + user + "' invalid credentials");
req.session.destroy();
res.status(401).send('User/Pass incorrect');
}
if (login(user, pass)) {
// Successful login
// Validate session and return OK
// Value stored in req.session allows us to identify the user in future requests
console.log(`Successful login for user '${user}'`);
req.session.loggedUser = user;
res.status(200).json({});
} else {
// Credentials are NOT valid
// Invalidate session and return error
console.log(`Invalid credentials for user '${user}'`);
req.session.destroy();
res.status(401).json({ message: 'Invalid credentials' });
}
});
// Logout
app.post('/api-login/logout', function (req, res) {
console.log("'" + req.session.loggedUser + "' has logged out");
req.session.destroy();
res.status(200).send();
app.post('/logout', function (req, res) {
console.log(`'${req.session.loggedUser}' has logged out`);
req.session.destroy();
res.status(200).json({});
});
// 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
var sessionName = req.body.sessionName;
app.post('/token', (req, res) => {
const {roomName, participantName} = req.body;
// Role associated to this user
var role = users.find(u => (u.user === req.session.loggedUser)).role;
if (!isLogged(req.session)) {
req.session.destroy();
res.status(401).json({ message: 'User not logged' });
return;
}
// 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 = JSON.stringify({ serverData: req.session.loggedUser });
console.log(
`Getting a token for room '${roomName}' and participant '${participantName}'`
);
console.log("Getting a token | {sessionName}={" + sessionName + "}");
if (!roomName || !participantName) {
res
.status(400)
.json({ message: 'roomName and participantName are required' });
return;
}
// Build connectionProperties object with the serverData and the role
var connectionProperties = {
data: serverData,
role: role
};
if (mapSessions[sessionName]) {
// Session already exists
console.log('Existing session ' + sessionName);
// Get the existing Session from the collection
var mySession = mapSessions[sessionName];
// Generate a new token asynchronously with the recently created connectionProperties
mySession.createConnection(connectionProperties)
.then(connection => {
// Store the new token in the collection of tokens
mapSessionNamesTokens[sessionName].push(connection.token);
// Return the token to the client
res.status(200).send({
0: connection.token
});
})
.catch(error => {
console.error(error);
});
} else {
// New session
console.log('New session ' + sessionName);
// 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] = [];
// Generate a new connection asynchronously with the recently created connectionProperties
session.createConnection(connectionProperties)
.then(connection => {
// Store the new token in the collection of tokens
mapSessionNamesTokens[sessionName].push(connection.token);
// Return the Token to the client
res.status(200).send({
0: connection.token
});
})
.catch(error => {
console.error(error);
});
})
.catch(error => {
console.error(error);
});
}
}
});
// Remove user from session
app.post('/api-sessions/remove-user', function (req, res) {
if (!isLogged(req.session)) {
req.session.destroy();
res.status(401).send('User not logged');
} else {
// Retrieve params from POST body
var sessionName = req.body.sessionName;
var token = req.body.token;
console.log('Removing user | {sessionName, token}={' + sessionName + ', ' + 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 + ': ' + 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);
res.status(500).send(msg);
}
}
const user = users.find((u) => u.user === req.session.loggedUser);
const {role, user: nickname} = user;
const canPublish = role === 'PUBLISHER';
const at = new AccessToken(LIVEKIT_API_KEY, LIVEKIT_API_SECRET, {
identity: participantName,
// add metadata to the token, which will be available in the participant's metadata
metadata: JSON.stringify({ livekitUrl: LIVEKIT_URL, nickname, role }),
});
at.addGrant({
roomJoin: true,
room: roomName,
canPublish,
canSubscribe: true,
});
res.status(200).json({ token: at.toJwt() });
});
/* REST API */
/* AUXILIARY METHODS */
function login(user, pass) {
return (users.find(u => (u.user === user) && (u.pass === pass)));
return users.find((u) => u.user === user && u.pass === pass);
}
function isLogged(session) {
return (session.loggedUser != null);
return session.loggedUser != null;
}
function getBasicAuth() {
return 'Basic ' + (new Buffer('OPENVIDUAPP:' + OPENVIDU_SECRET).toString('base64'));
}
// async function getRoom(roomName) {
// try {
// const rooms = await roomClient.listRooms(roomName);
// return rooms[0];
// } catch (error) {
// return undefined;
// }
// }
/* AUXILIARY METHODS */