Update all tutorials to use a server application

This commit is contained in:
pabloFuente 2022-08-08 19:35:46 +02:00
parent 7b16cd3dbb
commit b74e206023
46 changed files with 813 additions and 1196 deletions

View File

@ -12,7 +12,7 @@ RUN mkdir -p /var/www/openvidu-basic-screenshare && \
"https://github.com/OpenVidu/openvidu-tutorials/archive/v${OPENVIDU_TUTORIALS_VERSION}.tar.gz" && \
tar zxf /tmp/openvidu-tutorials.tar.gz -C /tmp && \
rm /tmp/openvidu-tutorials.tar.gz && \
cp -r /tmp/openvidu-tutorials*/openvidu-insecure-js-screen-share/web/* /var/www/openvidu-basic-screenshare && \
cp -r /tmp/openvidu-tutorials*/openvidu-js-screen-share/web/* /var/www/openvidu-basic-screenshare && \
rm -r /tmp/openvidu-tutorials* && \
chown -R nginx:nginx /var/www/openvidu-basic-screenshare

View File

@ -12,7 +12,7 @@ RUN mkdir -p /var/www/openvidu-basic-videoconference && \
"https://github.com/OpenVidu/openvidu-tutorials/archive/v${OPENVIDU_TUTORIALS_VERSION}.tar.gz" && \
tar zxf /tmp/openvidu-tutorials.tar.gz -C /tmp && \
rm /tmp/openvidu-tutorials.tar.gz && \
cp -r /tmp/openvidu-tutorials*/openvidu-insecure-js/web/* /var/www/openvidu-basic-videoconference && \
cp -r /tmp/openvidu-tutorials*/openvidu-js/web/* /var/www/openvidu-basic-videoconference && \
rm -r /tmp/openvidu-tutorials* && \
chown -R nginx:nginx /var/www/openvidu-basic-videoconference

View File

@ -71,11 +71,10 @@ function joinSession() {
// --- 4) Connect to the session with a valid user token ---
// 'getToken' method is simulating what your server-side should do.
// 'token' parameter should be retrieved and returned by your own backend
// Get a token from the OpenVidu deployment
getToken(mySessionId, role).then(token => {
// First param is the token got from OpenVidu Server. Second param can be retrieved by every user on event
// First param is the token got from the OpenVidu deployment. Second param can be retrieved by every user on event
// 'streamCreated' (property Stream.connection.data), and will be appended to DOM as the user's nickname
session.connect(token, { clientData: myUserName })
.then(() => {
@ -366,17 +365,20 @@ function initMainVideo(streamManager, userData) {
}
/**
* --------------------------
* SERVER-SIDE RESPONSIBILITY
* --------------------------
* These methods retrieve the mandatory user token from OpenVidu Server.
* This behavior MUST BE IN YOUR SERVER-SIDE IN PRODUCTION (by using
* the REST API, openvidu-java-client or openvidu-node-client):
* 1) Initialize a Session in OpenVidu Server (POST /openvidu/api/sessions)
* 2) Create a Connection in OpenVidu Server (POST /openvidu/api/sessions/<SESSION_ID>/connection)
* 3) The Connection.token must be consumed in Session.connect() method
* --------------------------------------------
* GETTING A TOKEN FROM YOUR APPLICATION SERVER
* --------------------------------------------
* The methods below request the creation of a Session and a Token to
* your application server. This keeps your OpenVidu deployment secure.
*
* In this sample code, there is no user control at all. Anybody could
* access your application server endpoints! In a real production
* environment, your application server must identify the user to allow
* access to the endpoints.
*
* Visit https://docs.openvidu.io/en/stable/application-server to learn
* more about the integration of OpenVidu in your application server.
*/
var OPENVIDU_SERVER_URL = "https://" + location.hostname + ":4443";

View File

@ -71,8 +71,7 @@ function joinRoom() {
// --- 4) Connect to the session with a valid user token ---
// 'getToken' method is simulating what your server-side should do.
// 'token' parameter should be retrieved and returned by your own backend
// Get a token from the OpenVidu deployment
getToken(sessionId).then(token => {
// Connect with the token
@ -258,17 +257,20 @@ function updateLayout() {
}
/**
* --------------------------
* SERVER-SIDE RESPONSIBILITY
* --------------------------
* These methods retrieve the mandatory user token from OpenVidu Server.
* This behavior MUST BE IN YOUR SERVER-SIDE IN PRODUCTION (by using
* the API REST, openvidu-java-client or openvidu-node-client):
* 1) Initialize a Session in OpenVidu Server (POST /openvidu/api/sessions)
* 2) Create a Connection in OpenVidu Server (POST /openvidu/api/sessions/<SESSION_ID>/connection)
* 3) The Connection.token must be consumed in Session.connect() method
* --------------------------------------------
* GETTING A TOKEN FROM YOUR APPLICATION SERVER
* --------------------------------------------
* The methods below request the creation of a Session and a Token to
* your application server. This keeps your OpenVidu deployment secure.
*
* In this sample code, there is no user control at all. Anybody could
* access your application server endpoints! In a real production
* environment, your application server must identify the user to allow
* access to the endpoints.
*
* Visit https://docs.openvidu.io/en/stable/application-server to learn
* more about the integration of OpenVidu in your application server.
*/
var OPENVIDU_SERVER_URL = "https://" + location.hostname + ":4443";
@ -305,17 +307,17 @@ function createSession(sessionId) { // See https://docs.openvidu.io/en/stable/re
}
function createToken(sessionId) { // See https://docs.openvidu.io/en/stable/reference-docs/REST-API/#post-openviduapisessionsltsession_idgtconnection
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: OPENVIDU_SERVER_URL + '/openvidu/api/sessions/' + sessionId + '/connection',
data: JSON.stringify({}),
headers: {
'Authorization': 'Basic ' + btoa('OPENVIDUAPP:' + OPENVIDU_SERVER_SECRET),
'Content-Type': 'application/json',
},
success: (response) => resolve(response.token),
error: (error) => reject(error)
});
});
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: OPENVIDU_SERVER_URL + '/openvidu/api/sessions/' + sessionId + '/connection',
data: JSON.stringify({}),
headers: {
'Authorization': 'Basic ' + btoa('OPENVIDUAPP:' + OPENVIDU_SERVER_SECRET),
'Content-Type': 'application/json',
},
success: (response) => resolve(response.token),
error: (error) => reject(error)
});
});
}

View File

@ -324,15 +324,19 @@ function offStreamAudioVolumeChangeSubscriber() {
/**
* --------------------------
* SERVER-SIDE RESPONSIBILITY
* --------------------------
* These methods retrieve the mandatory user token from OpenVidu Server.
* This behavior MUST BE IN YOUR SERVER-SIDE IN PRODUCTION (by using
* the API REST, openvidu-java-client or openvidu-node-client):
* 1) Initialize a Session in OpenVidu Server (POST /openvidu/api/sessions)
* 2) Create a Connection in OpenVidu Server (POST /openvidu/api/sessions/<SESSION_ID>/connection)
* 3) The Connection.token must be consumed in Session.connect() method
* --------------------------------------------
* GETTING A TOKEN FROM YOUR APPLICATION SERVER
* --------------------------------------------
* The methods below request the creation of a Session and a Token to
* your application server. This keeps your OpenVidu deployment secure.
*
* In this sample code, there is no user control at all. Anybody could
* access your application server endpoints! In a real production
* environment, your application server must identify the user to allow
* access to the endpoints.
*
* Visit https://docs.openvidu.io/en/stable/application-server to learn
* more about the integration of OpenVidu in your application server.
*/
var OPENVIDU_SERVER_URL = "https://" + location.hostname + ":4443";
@ -361,7 +365,7 @@ function createSession(sessionId) { // See https://docs.openvidu.io/en/stable/re
} else {
console.warn('No connection to OpenVidu Server. This may be a certificate error at ' + OPENVIDU_SERVER_URL);
if (window.confirm('No connection to OpenVidu Server. This may be a certificate error at \"' + OPENVIDU_SERVER_URL + '\"\n\nClick OK to navigate and accept it. ' +
'If no certificate warning is shown, then check that your OpenVidu Server is up and running at "' + OPENVIDU_SERVER_URL + '"')) {
'If no certificate warning is shown, then check that your OpenVidu Server is up and running at "' + OPENVIDU_SERVER_URL + '"')) {
location.assign(OPENVIDU_SERVER_URL + '/accept-certificate');
}
}

View File

@ -37,67 +37,54 @@ function leaveSession() {
}
window.onbeforeunload = function () {
if (session) session.disconnect()
if (session) session.disconnect();
};
/**
* --------------------------
* SERVER-SIDE RESPONSIBILITY
* --------------------------
* These methods retrieve the mandatory user token from OpenVidu Server.
* This behavior MUST BE IN YOUR SERVER-SIDE IN PRODUCTION (by using
* the API REST, openvidu-java-client or openvidu-node-client):
* 1) Initialize a Session in OpenVidu Server (POST /openvidu/api/sessions)
* 2) Create a Connection in OpenVidu Server (POST /openvidu/api/sessions/<SESSION_ID>/connection)
* 3) The Connection.token must be consumed in Session.connect() method
* --------------------------------------------
* GETTING A TOKEN FROM YOUR APPLICATION SERVER
* --------------------------------------------
* The methods below request the creation of a Session and a Token to
* your application server. This keeps your OpenVidu deployment secure.
*
* In this sample code, there is no user control at all. Anybody could
* access your application server endpoints! In a real production
* environment, your application server must identify the user to allow
* access to the endpoints.
*
* Visit https://docs.openvidu.io/en/stable/application-server to learn
* more about the integration of OpenVidu in your application server.
*/
var OPENVIDU_SERVER_URL = "https://" + location.hostname + ":4443";
var OPENVIDU_SERVER_SECRET = "MY_SECRET";
var APPLICATION_SERVER_URL = window.location.protocol + "//" + window.location.hostname + ":5000/";
function getToken(mySessionId) {
return createSession(mySessionId).then(sessionId => createToken(sessionId));
}
function createSession(sessionId) { // See https://docs.openvidu.io/en/stable/reference-docs/REST-API/#post-openviduapisessions
function createSession(sessionId) {
return new Promise((resolve, reject) => {
$.ajax({
type: "POST",
url: OPENVIDU_SERVER_URL + "/openvidu/api/sessions",
url: APPLICATION_SERVER_URL + "api/sessions",
data: JSON.stringify({ customSessionId: sessionId }),
headers: {
"Authorization": "Basic " + btoa("OPENVIDUAPP:" + OPENVIDU_SERVER_SECRET),
"Content-Type": "application/json"
},
success: response => resolve(response.id),
error: (error) => {
if (error.status === 409) {
resolve(sessionId);
} else {
console.warn('No connection to OpenVidu Server. This may be a certificate error at ' + OPENVIDU_SERVER_URL);
if (window.confirm('No connection to OpenVidu Server. This may be a certificate error at \"' + OPENVIDU_SERVER_URL + '\"\n\nClick OK to navigate and accept it. ' +
'If no certificate warning is shown, then check that your OpenVidu Server is up and running at "' + OPENVIDU_SERVER_URL + '"')) {
location.assign(OPENVIDU_SERVER_URL + '/accept-certificate');
}
}
}
headers: { "Content-Type": "application/json" },
success: response => resolve(response), // The sessionId
error: (error) => reject(error)
});
});
}
function createToken(sessionId) { // See https://docs.openvidu.io/en/stable/reference-docs/REST-API/#post-openviduapisessionsltsession_idgtconnection
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: OPENVIDU_SERVER_URL + '/openvidu/api/sessions/' + sessionId + '/connection',
data: JSON.stringify({}),
headers: {
'Authorization': 'Basic ' + btoa('OPENVIDUAPP:' + OPENVIDU_SERVER_SECRET),
'Content-Type': 'application/json',
},
success: (response) => resolve(response.token),
error: (error) => reject(error)
});
});
function createToken(sessionId) {
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: APPLICATION_SERVER_URL + 'api/sessions/' + sessionId + '/connections',
data: JSON.stringify({}),
headers: { "Content-Type": "application/json" },
success: (response) => resolve(response), // The token
error: (error) => reject(error)
});
});
}

View File

@ -6,9 +6,9 @@
[![][OpenViduLogo]](http://openvidu.io)
openvidu-insecure-angular
openvidu-angular
===
Visit [docs.openvidu.io/en/stable/tutorials/openvidu-insecure-angular/](http://docs.openvidu.io/en/stable/tutorials/openvidu-insecure-angular/)
Visit [docs.openvidu.io/en/stable/tutorials/openvidu-angular/](http://docs.openvidu.io/en/stable/tutorials/openvidu-angular/)
[OpenViduLogo]: https://secure.gravatar.com/avatar/5daba1d43042f2e4e85849733c8e5702?s=120

View File

@ -3,7 +3,7 @@
"version": 1,
"newProjectRoot": "projects",
"projects": {
"openvidu-insecure-angular": {
"openvidu-angular": {
"projectType": "application",
"schematics": {},
"root": "",
@ -13,7 +13,7 @@
"build": {
"builder": "@angular-devkit/build-angular:browser",
"options": {
"outputPath": "dist/openvidu-insecure-angular",
"outputPath": "dist/openvidu-angular",
"index": "src/index.html",
"main": "src/main.ts",
"polyfills": "src/polyfills.ts",
@ -62,18 +62,18 @@
"serve": {
"builder": "@angular-devkit/build-angular:dev-server",
"options": {
"browserTarget": "openvidu-insecure-angular:build"
"browserTarget": "openvidu-angular:build"
},
"configurations": {
"production": {
"browserTarget": "openvidu-insecure-angular:build:production"
"browserTarget": "openvidu-angular:build:production"
}
}
},
"extract-i18n": {
"builder": "@angular-devkit/build-angular:extract-i18n",
"options": {
"browserTarget": "openvidu-insecure-angular:build"
"browserTarget": "openvidu-angular:build"
}
},
"test": {
@ -110,15 +110,15 @@
"builder": "@angular-devkit/build-angular:protractor",
"options": {
"protractorConfig": "e2e/protractor.conf.js",
"devServerTarget": "openvidu-insecure-angular:serve"
"devServerTarget": "openvidu-angular:serve"
},
"configurations": {
"production": {
"devServerTarget": "openvidu-insecure-angular:serve:production"
"devServerTarget": "openvidu-angular:serve:production"
}
}
}
}
}},
"defaultProject": "openvidu-insecure-angular"
"defaultProject": "openvidu-angular"
}

View File

@ -10,7 +10,7 @@ describe('workspace-project App', () => {
it('should display welcome message', () => {
page.navigateTo();
expect(page.getTitleText()).toEqual('openvidu-insecure-angular app is running!');
expect(page.getTitleText()).toEqual('openvidu-angular app is running!');
});
afterEach(async () => {

View File

@ -16,7 +16,7 @@ module.exports = function (config) {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, './coverage/openvidu-insecure-angular'),
dir: require('path').join(__dirname, './coverage/openvidu-angular'),
reports: ['html', 'lcovonly', 'text-summary'],
fixWebpackSourcePaths: true
},

View File

@ -1,5 +1,5 @@
{
"name": "openvidu-insecure-angular",
"name": "openvidu-angular",
"version": "2.22.0",
"license": "Apache-2.0",
"scripts": {

View File

@ -1,8 +1,6 @@
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { HttpClient } from '@angular/common/http';
import { Component, HostListener, OnDestroy } from '@angular/core';
import { OpenVidu, Publisher, Session, StreamEvent, StreamManager, Subscriber } from 'openvidu-browser';
import { throwError as observableThrowError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Component({
@ -12,8 +10,7 @@ import { catchError } from 'rxjs/operators';
})
export class AppComponent implements OnDestroy {
OPENVIDU_SERVER_URL = 'https://' + location.hostname + ':4443';
OPENVIDU_SERVER_SECRET = 'MY_SECRET';
APPLICATION_SERVER_URL = window.location.protocol + '//' + window.location.hostname + ':5000/';
// OpenVidu objects
OV: OpenVidu;
@ -79,11 +76,10 @@ export class AppComponent implements OnDestroy {
// --- 4) Connect to the session with a valid user token ---
// 'getToken' method is simulating what your server-side should do.
// 'token' parameter should be retrieved and returned by your own backend
// Get a token from the OpenVidu deployment
this.getToken().then(token => {
// First param is the token got from OpenVidu Server. Second param can be retrieved by every user on event
// First param is the token got from the OpenVidu deployment. Second param can be retrieved by every user on event
// 'streamCreated' (property Stream.connection.data), and will be appended to DOM as the user's nickname
this.session.connect(token, { clientData: this.myUserName })
.then(() => {
@ -150,81 +146,41 @@ export class AppComponent implements OnDestroy {
}
/**
* --------------------------
* SERVER-SIDE RESPONSIBILITY
* --------------------------
* This method retrieve the mandatory user token from OpenVidu Server,
* in this case making use Angular http API.
* This behavior MUST BE IN YOUR SERVER-SIDE IN PRODUCTION. In this case:
* 1) Initialize a Session in OpenVidu Server (POST /openvidu/api/sessions)
* 2) Create a Connection in OpenVidu Server (POST /openvidu/api/sessions/<SESSION_ID>/connection)
* 3) The Connection.token must be consumed in Session.connect() method
* --------------------------------------------
* GETTING A TOKEN FROM YOUR APPLICATION SERVER
* --------------------------------------------
* The methods below request the creation of a Session and a Token to
* your application server. This keeps your OpenVidu deployment secure.
*
* In this sample code, there is no user control at all. Anybody could
* access your application server endpoints! In a real production
* environment, your application server must identify the user to allow
* access to the endpoints.
*
* Visit https://docs.openvidu.io/en/stable/application-server to learn
* more about the integration of OpenVidu in your application server.
*/
getToken(): Promise<string> {
return this.createSession(this.mySessionId).then(
sessionId => {
return this.createToken(sessionId);
})
async getToken(): Promise<string> {
const sessionId = await this.createSession(this.mySessionId);
return await this.createToken(sessionId);
}
createSession(sessionId) {
return new Promise((resolve, reject) => {
const body = JSON.stringify({ customSessionId: sessionId });
const options = {
headers: new HttpHeaders({
'Authorization': 'Basic ' + btoa('OPENVIDUAPP:' + this.OPENVIDU_SERVER_SECRET),
'Content-Type': 'application/json'
})
};
return this.httpClient.post(this.OPENVIDU_SERVER_URL + '/openvidu/api/sessions', body, options)
.pipe(
catchError(error => {
if (error.status === 409) {
resolve(sessionId);
} else {
console.warn('No connection to OpenVidu Server. This may be a certificate error at ' + this.OPENVIDU_SERVER_URL);
if (window.confirm('No connection to OpenVidu Server. This may be a certificate error at \"' + this.OPENVIDU_SERVER_URL +
'\"\n\nClick OK to navigate and accept it. If no certificate warning is shown, then check that your OpenVidu Server' +
'is up and running at "' + this.OPENVIDU_SERVER_URL + '"')) {
location.assign(this.OPENVIDU_SERVER_URL + '/accept-certificate');
}
}
return observableThrowError(error);
})
)
.subscribe(response => {
console.log(response);
resolve(response['id']);
});
});
return this.httpClient.post(
this.APPLICATION_SERVER_URL + 'api/sessions',
{ customSessionId: sessionId },
{ headers: { 'Content-Type': 'application/json' }, responseType: 'text' }
).toPromise();
}
createToken(sessionId): Promise<string> {
return new Promise((resolve, reject) => {
const body = {};
const options = {
headers: new HttpHeaders({
'Authorization': 'Basic ' + btoa('OPENVIDUAPP:' + this.OPENVIDU_SERVER_SECRET),
'Content-Type': 'application/json'
})
};
return this.httpClient.post(this.OPENVIDU_SERVER_URL + '/openvidu/api/sessions/' + sessionId + '/connection', body, options)
.pipe(
catchError(error => {
reject(error);
return observableThrowError(error);
})
)
.subscribe(response => {
console.log(response);
resolve(response['token']);
});
});
createToken(sessionId) {
return this.httpClient.post(
this.APPLICATION_SERVER_URL + 'api/sessions/' + sessionId + '/connections',
{ customSessionId: sessionId },
{ headers: { 'Content-Type': 'application/json' }, responseType: 'text' }
).toPromise();
}
}

View File

@ -2,7 +2,7 @@
<head>
<meta charset="utf-8">
<title>openvidu-insecure-angular</title>
<title>openvidu-angular</title>
<link rel="shortcut icon" href="assets/images/favicon.ico">
<base href="/">
@ -21,9 +21,9 @@
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/"><img class="demo-logo" src="assets/images/openvidu_vert_white_bg_trans_cropped.png"/> Insecure Angular</a>
<a class="navbar-brand nav-icon" href="https://github.com/OpenVidu/openvidu-tutorials/tree/master/openvidu-insecure-angular" 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-insecure-angular/" title="Documentation" target="_blank"><i class="fa fa-book" aria-hidden="true"></i></a>
<a class="navbar-brand" href="/"><img class="demo-logo" src="assets/images/openvidu_vert_white_bg_trans_cropped.png"/> Angular</a>
<a class="navbar-brand nav-icon" href="https://github.com/OpenVidu/openvidu-tutorials/tree/master/openvidu-angular" 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-angular/" title="Documentation" target="_blank"><i class="fa fa-book" aria-hidden="true"></i></a>
</div>
</div>
</nav>

View File

@ -6,9 +6,9 @@
[![][OpenViduLogo]](http://openvidu.io)
openvidu-insecure-js-screen-share
openvidu-js-screen-share
===
Visit [docs.openvidu.io/en/stable/tutorials/openvidu-insecure-js-screen-share/](http://docs.openvidu.io/en/stable/tutorials/openvidu-insecure-js-screen-share/)
Visit [docs.openvidu.io/en/stable/tutorials/openvidu-js-screen-share/](http://docs.openvidu.io/en/stable/tutorials/openvidu-js-screen-share/)
[OpenViduLogo]: https://secure.gravatar.com/avatar/5daba1d43042f2e4e85849733c8e5702?s=120

View File

@ -4,12 +4,12 @@ RUN apk update && \
# apk add wget && \
rm -rf /var/cache/apk/*
# Install insecure-js
COPY ./web /var/www/openvidu-insecure-js-screen-share
RUN chown -R nginx:nginx /var/www/openvidu-insecure-js-screen-share
# Install openvidu-js-screen-share
COPY ./web /var/www/openvidu-js-screen-share
RUN chown -R nginx:nginx /var/www/openvidu-js-screen-share
# Nginx conf
COPY ./docker/openvidu-insecure-js-screen-share.conf /etc/nginx/conf.d/default.conf
COPY ./docker/openvidu-js-screen-share.conf /etc/nginx/conf.d/default.conf
# Entrypoint
COPY ./docker/entrypoint.sh /usr/local/bin

View File

@ -2,7 +2,7 @@
pushd ../
docker build -f docker/Dockerfile -t openvidu/openvidu-insecure-js-screen-share-demo .
docker tag openvidu/openvidu-insecure-js-screen-share-demo:latest openvidu/openvidu-insecure-js-screen-share-demo:2.20.0
docker build -f docker/Dockerfile -t openvidu/openvidu-js-screen-share-demo .
docker tag openvidu/openvidu-js-screen-share-demo:latest openvidu/openvidu-js-screen-share-demo:2.20.0
popd

View File

@ -2,9 +2,8 @@ version: '3.1'
services:
app:
image: openvidu/openvidu-insecure-js-screen-share-demo:2.20.0
image: openvidu/openvidu-js-screen-share-demo:2.22.0
restart: on-failure
network_mode: host
environment:
- OPENVIDU_URL=https://${DOMAIN_OR_PUBLIC_IP:-}:${HTTPS_PORT:-443}
- OPENVIDU_SECRET=${OPENVIDU_SECRET}
- APPLICATION_URL=https://${DOMAIN_OR_PUBLIC_IP:-}:${HTTPS_PORT:-443}

View File

@ -3,10 +3,10 @@
[ ! -z "${OPENVIDU_URL}" ] && echo "OPENVIDU_URL: ${OPENVIDU_URL}" || echo "OPENVIDU_URL: default"
[ ! -z "${OPENVIDU_SECRET}" ] && echo "OPENVIDU_SECRET: ${OPENVIDU_SECRET}" || echo "OPENVIDU_SECRET: default"
sed -i "s|^var OPENVIDU_SERVER_URL =.*$|var OPENVIDU_SERVER_URL = \"${OPENVIDU_URL}\";|" /var/www/openvidu-insecure-js-screen-share/app.js
sed -i "s|^var OPENVIDU_SERVER_URL =.*$|var OPENVIDU_SERVER_URL = \"${OPENVIDU_URL}\";|" /var/www/openvidu-js-screen-share/app.js
if [ ! -z "${OPENVIDU_SECRET}" ]; then
sed -i "s/^var OPENVIDU_SERVER_SECRET =.*$/var OPENVIDU_SERVER_SECRET = \"${OPENVIDU_SECRET}\";/" /var/www/openvidu-insecure-js-screen-share/app.js
sed -i "s/^var OPENVIDU_SERVER_SECRET =.*$/var OPENVIDU_SERVER_SECRET = \"${OPENVIDU_SECRET}\";/" /var/www/openvidu-js-screen-share/app.js
fi
# Run nginx

View File

@ -1,5 +1,5 @@
server {
listen 5442;
root /var/www/openvidu-insecure-js-screen-share;
root /var/www/openvidu-js-screen-share;
}

View File

@ -33,7 +33,8 @@ function joinSession() {
// --- 3) Specify the actions when events of type 'streamCreated' take
// --- place in the session. The reason why we're using two different objects
// --- is to handle diferently the subscribers when it is of 'camera' type, or 'SCREEN' type ---
// --- is to handle diferently the subscribers when it is of 'CAMERA' type, or 'SCREEN' type ---
// ------- 3.1) Handle subscribers of 'CAMERA' type
sessionCamera.on('streamCreated', event => {
if (event.stream.typeOfVideo == "CAMERA") {
@ -46,6 +47,7 @@ function joinSession() {
});
}
});
// ------- 3.2) Handle subscribers of 'Screen' type
sessionScreen.on('streamCreated', event => {
if (event.stream.typeOfVideo == "SCREEN") {
@ -71,14 +73,12 @@ function joinSession() {
});
// --- 4) Connect to the session with a valid user token. ---
// 'getToken' method is simulating what your server-side should do.
// 'token' parameter should be retrieved and returned by your own backend
// --- 4) Connect to the session with two different tokens: one for the camera and other for the screen ---
// -------4.1 Get the token for the 'sessionCamera' object
// --- 4.1) Get the token for the 'sessionCamera' object
getToken(mySessionId).then(token => {
// First param is the token got from OpenVidu Server. Second param can be retrieved by every user on event
// First param is the token got from the OpenVidu deployment. Second param can be retrieved by every user on event
// 'streamCreated' (property Stream.connection.data), and will be appended to DOM as the user's nickname
sessionCamera.connect(token, { clientData: myUserName })
.then(() => {
@ -120,7 +120,7 @@ function joinSession() {
});
});
// -------4.1 Get the token for the 'sessionScreen' object
// --- 4.2) Get the token for the 'sessionScreen' object
getToken(mySessionId).then((tokenScreen) => {
// Create a token for screen share
sessionScreen.connect(tokenScreen, { clientData: myUserName }).then(() => {
@ -132,16 +132,16 @@ function joinSession() {
});
}
// --- 9). Create a function to be called when the 'Screen share' button is clicked.
// --- 9) Function to be called when the 'Screen share' button is clicked
function publishScreenShare() {
// --- 9.1) To create a publisherScreen it is very important that the property 'videoSource' is set to 'screen'
// --- 9.1) To create a publisherScreen set the property 'videoSource' to 'screen'
var publisherScreen = OVScreen.initPublisher("container-screens", { videoSource: "screen" });
// --- 9.2) If the user grants access to the screen share function, publish the screen stream
// --- 9.2) Publish the screen share stream only after the user grants permission to the browser
publisherScreen.once('accessAllowed', (event) => {
document.getElementById('buttonScreenShare').style.visibility = 'hidden';
screensharing = true;
// It is very important to define what to do when the stream ends.
// If the user closes the shared window or stops sharing it, unpublish the stream
publisherScreen.stream.getMediaStream().getVideoTracks()[0].addEventListener('ended', () => {
console.log('User pressed the "Stop sharing" button');
sessionScreen.unpublish(publisherScreen);
@ -178,17 +178,17 @@ function leaveSession() {
screensharing = false;
}
window.onbeforeunload = function () {
if (sessionCamera) sessionCamera.disconnect();
if (sessionScreen) sessionScreen.disconnect();
};
/* APPLICATION SPECIFIC METHODS */
window.addEventListener('load', function () {
generateParticipantInfo();
});
window.onbeforeunload = function () {
if (sessionCamera) sessionCamera.disconnect();
if (sessionScreen) sessionScreen.disconnect();
};
function generateParticipantInfo() {
document.getElementById("sessionId").value = "SessionScreenA";
document.getElementById("userName").value = "Participant" + Math.floor(Math.random() * 100);
@ -247,62 +247,49 @@ function initMainVideo(videoElement, userData) {
/**
* --------------------------
* SERVER-SIDE RESPONSIBILITY
* --------------------------
* These methods retrieve the mandatory user token from OpenVidu Server.
* This behavior MUST BE IN YOUR SERVER-SIDE IN PRODUCTION (by using
* the API REST, openvidu-java-client or openvidu-node-client):
* 1) Initialize a Session in OpenVidu Server (POST /openvidu/api/sessions)
* 2) Create a Connection in OpenVidu Server (POST /openvidu/api/sessions/<SESSION_ID>/connection)
* 3) The Connection.token must be consumed in Session.connect() method
* --------------------------------------------
* GETTING A TOKEN FROM YOUR APPLICATION SERVER
* --------------------------------------------
* The methods below request the creation of a Session and a Token to
* your application server. This keeps your OpenVidu deployment secure.
*
* In this sample code, there is no user control at all. Anybody could
* access your application server endpoints! In a real production
* environment, your application server must identify the user to allow
* access to the endpoints.
*
* Visit https://docs.openvidu.io/en/stable/application-server to learn
* more about the integration of OpenVidu in your application server.
*/
var OPENVIDU_SERVER_URL = "https://" + location.hostname + ":4443";
var OPENVIDU_SERVER_SECRET = "MY_SECRET";
var APPLICATION_SERVER_URL = window.location.protocol + "//" + window.location.hostname + ":5000/";
function getToken(mySessionId) {
return createSession(mySessionId).then(sessionId => createToken(sessionId));
}
function createSession(sessionId) { // See https://docs.openvidu.io/en/stable/reference-docs/REST-API/#post-openviduapisessions
return new Promise((resolve, reject) => {
$.ajax({
type: "POST",
url: OPENVIDU_SERVER_URL + "/openvidu/api/sessions",
data: JSON.stringify({ customSessionId: sessionId }),
headers: {
"Authorization": "Basic " + btoa("OPENVIDUAPP:" + OPENVIDU_SERVER_SECRET),
"Content-Type": "application/json"
},
success: response => resolve(response.id),
error: (error) => {
if (error.status === 409) {
resolve(sessionId);
} else {
console.warn('No connection to OpenVidu Server. This may be a certificate error at ' + OPENVIDU_SERVER_URL);
if (window.confirm('No connection to OpenVidu Server. This may be a certificate error at \"' + OPENVIDU_SERVER_URL + '\"\n\nClick OK to navigate and accept it. ' +
'If no certificate warning is shown, then check that your OpenVidu Server is up and running at "' + OPENVIDU_SERVER_URL + '"')) {
location.assign(OPENVIDU_SERVER_URL + '/accept-certificate');
}
}
}
});
});
}
function createToken(sessionId) { // See https://docs.openvidu.io/en/stable/reference-docs/REST-API/#post-openviduapisessionsltsession_idgtconnection
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: OPENVIDU_SERVER_URL + '/openvidu/api/sessions/' + sessionId + '/connection',
data: JSON.stringify({}),
headers: {
'Authorization': 'Basic ' + btoa('OPENVIDUAPP:' + OPENVIDU_SERVER_SECRET),
'Content-Type': 'application/json',
},
success: (response) => resolve(response.token),
error: (error) => reject(error)
});
});
}
function getToken(mySessionId) {
return createSession(mySessionId).then(sessionId => createToken(sessionId));
}
function createSession(sessionId) {
return new Promise((resolve, reject) => {
$.ajax({
type: "POST",
url: APPLICATION_SERVER_URL + "api/sessions",
data: JSON.stringify({ customSessionId: sessionId }),
headers: { "Content-Type": "application/json" },
success: response => resolve(response), // The sessionId
error: (error) => reject(error)
});
});
}
function createToken(sessionId) {
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: APPLICATION_SERVER_URL + 'api/sessions/' + sessionId + '/connections',
data: JSON.stringify({}),
headers: { "Content-Type": "application/json" },
success: (response) => resolve(response), // The token
error: (error) => reject(error)
});
});
}

View File

@ -1,7 +1,7 @@
<html>
<head>
<title>openvidu-insecure-js-screen-share</title>
<title>openvidu-js-screen-share</title>
<meta name="viewport" content="width=device-width, initial-scale=1" charset="utf-8">
<link rel="shortcut icon" href="resources/images/favicon.ico" type="image/x-icon">
@ -23,9 +23,9 @@
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/"><img class="demo-logo" src="resources/images/openvidu_vert_white_bg_trans_cropped.png"/> Insecure JS Screen Share</a>
<a class="navbar-brand nav-icon" href="https://github.com/OpenVidu/openvidu-tutorials/tree/master/openvidu-insecure-js-screen-share" title="GitHub Repository" target="_blank"><i class="fa fa-github" aria-hidden="true"></i></a>
<a class="navbar-brand nav-icon" href="https://docs.openvidu.io/en/stable/tutorials/openvidu-insecure-js-screen-share/" title="Documentation" target="_blank"><i class="fa fa-book" aria-hidden="true"></i></a>
<a class="navbar-brand" href="/"><img class="demo-logo" src="resources/images/openvidu_vert_white_bg_trans_cropped.png"/> JS Screen Share</a>
<a class="navbar-brand nav-icon" href="https://github.com/OpenVidu/openvidu-tutorials/tree/master/openvidu-js-screen-share" title="GitHub Repository" target="_blank"><i class="fa fa-github" aria-hidden="true"></i></a>
<a class="navbar-brand nav-icon" href="https://docs.openvidu.io/en/stable/tutorials/openvidu-js-screen-share/" title="Documentation" target="_blank"><i class="fa fa-book" aria-hidden="true"></i></a>
</div>
</div>
</nav>

View File

@ -6,9 +6,9 @@
[![][OpenViduLogo]](http://openvidu.io)
openvidu-insecure-js
openvidu-js
===
Visit [docs.openvidu.io/en/stable/tutorials/openvidu-insecure-js/](http://docs.openvidu.io/en/stable/tutorials/openvidu-insecure-js/)
Visit [docs.openvidu.io/en/stable/tutorials/openvidu-js/](http://docs.openvidu.io/en/stable/tutorials/openvidu-js/)
[OpenViduLogo]: https://secure.gravatar.com/avatar/5daba1d43042f2e4e85849733c8e5702?s=120

View File

@ -4,12 +4,12 @@ RUN apk update && \
# apk add wget && \
rm -rf /var/cache/apk/*
# Install insecure-js
COPY ./web /var/www/openvidu-insecure-js
RUN chown -R nginx:nginx /var/www/openvidu-insecure-js
# Install openvidu-js
COPY ./web /var/www/openvidu-js
RUN chown -R nginx:nginx /var/www/openvidu-js
# Nginx conf
COPY ./docker/openvidu-insecure-js.conf /etc/nginx/conf.d/default.conf
COPY ./docker/openvidu-js.conf /etc/nginx/conf.d/default.conf
# Entrypoint
COPY ./docker/entrypoint.sh /usr/local/bin

View File

@ -2,5 +2,5 @@
pushd ../
docker build -f docker/Dockerfile -t openvidu/openvidu-insecure-js-demo .
docker tag openvidu/openvidu-insecure-js-demo:latest openvidu/openvidu-insecure-js-demo:2.18.0
docker build -f docker/Dockerfile -t openvidu/openvidu-js-demo .
docker tag openvidu/openvidu-js-demo:latest openvidu/openvidu-js-demo:2.18.0

View File

@ -2,9 +2,8 @@ version: '3.1'
services:
app:
image: openvidu/openvidu-insecure-js-demo:2.18.0
image: openvidu/openvidu-js-demo:2.22.0
restart: on-failure
network_mode: host
environment:
- OPENVIDU_URL=https://${DOMAIN_OR_PUBLIC_IP:-}:${HTTPS_PORT:-443}
- OPENVIDU_SECRET=${OPENVIDU_SECRET}
- APPLICATION_URL=https://${DOMAIN_OR_PUBLIC_IP:-}:${HTTPS_PORT:-443}

View File

@ -3,10 +3,10 @@
[ ! -z "${OPENVIDU_URL}" ] && echo "OPENVIDU_URL: ${OPENVIDU_URL}" || echo "OPENVIDU_URL: default"
[ ! -z "${OPENVIDU_SECRET}" ] && echo "OPENVIDU_SECRET: ${OPENVIDU_SECRET}" || echo "OPENVIDU_SECRET: default"
sed -i "s|^var OPENVIDU_SERVER_URL =.*$|var OPENVIDU_SERVER_URL = \"${OPENVIDU_URL}\";|" /var/www/openvidu-insecure-js/app.js
sed -i "s|^var OPENVIDU_SERVER_URL =.*$|var OPENVIDU_SERVER_URL = \"${OPENVIDU_URL}\";|" /var/www/openvidu-js/app.js
if [ ! -z "${OPENVIDU_SECRET}" ]; then
sed -i "s/^var OPENVIDU_SERVER_SECRET =.*$/var OPENVIDU_SERVER_SECRET = \"${OPENVIDU_SECRET}\";/" /var/www/openvidu-insecure-js/app.js
sed -i "s/^var OPENVIDU_SERVER_SECRET =.*$/var OPENVIDU_SERVER_SECRET = \"${OPENVIDU_SECRET}\";/" /var/www/openvidu-js/app.js
fi
# Run nginx

View File

@ -1,5 +1,5 @@
server {
listen 5442;
root /var/www/openvidu-insecure-js;
root /var/www/openvidu-js;
}

View File

@ -48,11 +48,10 @@ function joinSession() {
// --- 4) Connect to the session with a valid user token ---
// 'getToken' method is simulating what your server-side should do.
// 'token' parameter should be retrieved and returned by your own backend
// Get a token from the OpenVidu deployment
getToken(mySessionId).then(token => {
// First param is the token got from OpenVidu Server. Second param can be retrieved by every user on event
// First param is the token got from the OpenVidu deployment. Second param can be retrieved by every user on event
// 'streamCreated' (property Stream.connection.data), and will be appended to DOM as the user's nickname
session.connect(token, { clientData: myUserName })
.then(() => {
@ -111,6 +110,9 @@ function leaveSession() {
document.getElementById('session').style.display = 'none';
}
window.onbeforeunload = function () {
if (session) session.disconnect();
};
/* APPLICATION SPECIFIC METHODS */
@ -119,10 +121,6 @@ window.addEventListener('load', function () {
generateParticipantInfo();
});
window.onbeforeunload = function () {
if (session) session.disconnect();
};
function generateParticipantInfo() {
document.getElementById("sessionId").value = "SessionA";
document.getElementById("userName").value = "Participant" + Math.floor(Math.random() * 100);
@ -178,64 +176,50 @@ function initMainVideo(videoElement, userData) {
}
/**
* --------------------------
* SERVER-SIDE RESPONSIBILITY
* --------------------------
* These methods retrieve the mandatory user token from OpenVidu Server.
* This behavior MUST BE IN YOUR SERVER-SIDE IN PRODUCTION (by using
* the API REST, openvidu-java-client or openvidu-node-client):
* 1) Initialize a Session in OpenVidu Server (POST /openvidu/api/sessions)
* 2) Create a Connection in OpenVidu Server (POST /openvidu/api/sessions/<SESSION_ID>/connection)
* 3) The Connection.token must be consumed in Session.connect() method
* --------------------------------------------
* GETTING A TOKEN FROM YOUR APPLICATION SERVER
* --------------------------------------------
* The methods below request the creation of a Session and a Token to
* your application server. This keeps your OpenVidu deployment secure.
*
* In this sample code, there is no user control at all. Anybody could
* access your application server endpoints! In a real production
* environment, your application server must identify the user to allow
* access to the endpoints.
*
* Visit https://docs.openvidu.io/en/stable/application-server to learn
* more about the integration of OpenVidu in your application server.
*/
var OPENVIDU_SERVER_URL = "https://" + location.hostname + ":4443";
var OPENVIDU_SERVER_SECRET = "MY_SECRET";
var APPLICATION_SERVER_URL = window.location.protocol + "//" + window.location.hostname + ":5000/";
function getToken(mySessionId) {
return createSession(mySessionId).then(sessionId => createToken(sessionId));
}
function createSession(sessionId) { // See https://docs.openvidu.io/en/stable/reference-docs/REST-API/#post-openviduapisessions
function createSession(sessionId) {
return new Promise((resolve, reject) => {
$.ajax({
type: "POST",
url: OPENVIDU_SERVER_URL + "/openvidu/api/sessions",
url: APPLICATION_SERVER_URL + "api/sessions",
data: JSON.stringify({ customSessionId: sessionId }),
headers: {
"Authorization": "Basic " + btoa("OPENVIDUAPP:" + OPENVIDU_SERVER_SECRET),
"Content-Type": "application/json"
},
success: response => resolve(response.id),
error: (error) => {
if (error.status === 409) {
resolve(sessionId);
} else {
console.warn('No connection to OpenVidu Server. This may be a certificate error at ' + OPENVIDU_SERVER_URL);
if (window.confirm('No connection to OpenVidu Server. This may be a certificate error at \"' + OPENVIDU_SERVER_URL + '\"\n\nClick OK to navigate and accept it. ' +
'If no certificate warning is shown, then check that your OpenVidu Server is up and running at "' + OPENVIDU_SERVER_URL + '"')) {
location.assign(OPENVIDU_SERVER_URL + '/accept-certificate');
}
}
}
headers: { "Content-Type": "application/json" },
success: response => resolve(response), // The sessionId
error: (error) => reject(error)
});
});
}
function createToken(sessionId) { // See https://docs.openvidu.io/en/stable/reference-docs/REST-API/#post-openviduapisessionsltsession_idgtconnection
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: OPENVIDU_SERVER_URL + '/openvidu/api/sessions/' + sessionId + '/connection',
data: JSON.stringify({}),
headers: {
'Authorization': 'Basic ' + btoa('OPENVIDUAPP:' + OPENVIDU_SERVER_SECRET),
'Content-Type': 'application/json',
},
success: (response) => resolve(response.token),
error: (error) => reject(error)
});
});
function createToken(sessionId) {
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: APPLICATION_SERVER_URL + 'api/sessions/' + sessionId + '/connections',
data: JSON.stringify({}),
headers: { "Content-Type": "application/json" },
success: (response) => resolve(response), // The token
error: (error) => reject(error)
});
});
}

View File

@ -1,7 +1,7 @@
<html>
<head>
<title>openvidu-insecure-js</title>
<title>openvidu-js</title>
<meta name="viewport" content="width=device-width, initial-scale=1" charset="utf-8">
<link rel="shortcut icon" href="resources/images/favicon.ico" type="image/x-icon">
@ -23,9 +23,9 @@
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/"><img class="demo-logo" src="resources/images/openvidu_vert_white_bg_trans_cropped.png"/> Insecure JS</a>
<a class="navbar-brand nav-icon" href="https://github.com/OpenVidu/openvidu-tutorials/tree/master/openvidu-insecure-js" 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-insecure-js/" title="Documentation" target="_blank"><i class="fa fa-book" aria-hidden="true"></i></a>
<a class="navbar-brand" href="/"><img class="demo-logo" src="resources/images/openvidu_vert_white_bg_trans_cropped.png"/> JS</a>
<a class="navbar-brand nav-icon" href="https://github.com/OpenVidu/openvidu-tutorials/tree/master/openvidu-js" 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-js/" title="Documentation" target="_blank"><i class="fa fa-book" aria-hidden="true"></i></a>
</div>
</div>
</nav>

View File

@ -6,9 +6,9 @@
[![][OpenViduLogo]](http://openvidu.io)
openvidu-insecure-react
openvidu-react
===
Visit [docs.openvidu.io/en/stable/tutorials/openvidu-insecure-react/](http://docs.openvidu.io/en/stable/tutorials/openvidu-insecure-react/)
Visit [docs.openvidu.io/en/stable/tutorials/openvidu-react/](http://docs.openvidu.io/en/stable/tutorials/openvidu-react/)
[OpenViduLogo]: https://secure.gravatar.com/avatar/5daba1d43042f2e4e85849733c8e5702?s=120

View File

@ -1,5 +1,5 @@
{
"name": "openvidu-insecure-react",
"name": "openvidu-react",
"version": "2.22.0",
"private": true,
"dependencies": {

View File

@ -31,7 +31,7 @@
crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<!-- Bootstrap -->
<title>openvidu-insecure-react App</title>
<title>openvidu-react App</title>
</head>
<body>
@ -42,11 +42,11 @@
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/">
<img class="demo-logo" src="resources/images/openvidu_vert_white_bg_trans_cropped.png" /> Insecure React</a>
<a class="navbar-brand nav-icon" href="https://github.com/OpenVidu/openvidu-tutorials/tree/master/openvidu-insecure-react" title="GitHub Repository" target="_blank">
<img class="demo-logo" src="resources/images/openvidu_vert_white_bg_trans_cropped.png" /> React</a>
<a class="navbar-brand nav-icon" href="https://github.com/OpenVidu/openvidu-tutorials/tree/master/openvidu-react" 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-insecure-react/" title="Documentation" target="_blank">
<a class="navbar-brand nav-icon" href="http://www.docs.openvidu.io/en/stable/tutorials/openvidu-react/" title="Documentation" target="_blank">
<i class="fa fa-book" aria-hidden="true"></i>
</a>
</div>

View File

@ -1,22 +1,23 @@
import axios from 'axios';
import { OpenVidu } from 'openvidu-browser';
import axios from 'axios';
import React, { Component } from 'react';
import './App.css';
import UserVideoComponent from './UserVideoComponent';
const OPENVIDU_SERVER_URL = 'https://' + window.location.hostname + ':4443';
const OPENVIDU_SERVER_SECRET = 'MY_SECRET';
const APPLICATION_SERVER_URL = window.location.protocol + "//" + window.location.hostname + ":5000/";
class App extends Component {
constructor(props) {
super(props);
// These properties are in the state's component in order to re-render the HTML whenever their values change
this.state = {
mySessionId: 'SessionA',
myUserName: 'Participant' + Math.floor(Math.random() * 100),
session: undefined,
mainStreamManager: undefined,
mainStreamManager: undefined, // Main video of the page. Will be the 'publisher' or one of the 'subscribers'
publisher: undefined,
subscribers: [],
};
@ -117,27 +118,20 @@ class App extends Component {
// --- 4) Connect to the session with a valid user token ---
// 'getToken' method is simulating what your server-side should do.
// 'token' parameter should be retrieved and returned by your own backend
// Get a token from the OpenVidu deployment
this.getToken().then((token) => {
// First param is the token got from OpenVidu Server. Second param can be retrieved by every user on event
// First param is the token got from the OpenVidu deployment. Second param can be retrieved by every user on event
// 'streamCreated' (property Stream.connection.data), and will be appended to DOM as the user's nickname
mySession
.connect(
token,
{ clientData: this.state.myUserName },
)
mySession.connect(token, { clientData: this.state.myUserName })
.then(async () => {
var devices = await this.OV.getDevices();
var videoDevices = devices.filter(device => device.kind === 'videoinput');
// --- 5) Get your own camera stream ---
// Init a publisher passing undefined as targetElement (we don't want OpenVidu to insert a video
// element: we will manage it on our own) and with the desired properties
let publisher = this.OV.initPublisher(undefined, {
let publisher = await this.OV.initPublisherAsync(undefined, {
audioSource: undefined, // The source of audio. If undefined default microphone
videoSource: videoDevices[0].deviceId, // The source of video. If undefined default webcam
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
@ -150,9 +144,15 @@ class App extends Component {
mySession.publish(publisher);
// Obtain the current video device in use
var devices = await this.OV.getDevices();
var videoDevices = devices.filter(device => device.kind === 'videoinput');
var currentVideoDeviceId = publisher.stream.getMediaStream().getVideoTracks()[0].getSettings().deviceId;
var currentVideoDevice = videoDevices.find(device => device.deviceId === currentVideoDeviceId);
// Set the main video in the page to display our webcam and store our Publisher
this.setState({
currentVideoDevice: videoDevices[0],
currentVideoDevice: currentVideoDevice,
mainStreamManager: publisher,
publisher: publisher,
});
@ -188,15 +188,15 @@ class App extends Component {
}
async switchCamera() {
try{
try {
const devices = await this.OV.getDevices()
var videoDevices = devices.filter(device => device.kind === 'videoinput');
if(videoDevices && videoDevices.length > 1) {
if (videoDevices && videoDevices.length > 1) {
var newVideoDevice = videoDevices.filter(device => device.deviceId !== this.state.currentVideoDevice.deviceId)
if (newVideoDevice.length > 0){
if (newVideoDevice.length > 0) {
// Creating a new publisher with specific videoSource
// In mobile devices the default and first camera is the front one
var newPublisher = this.OV.initPublisher(undefined, {
@ -211,15 +211,15 @@ class App extends Component {
await this.state.session.publish(newPublisher)
this.setState({
currentVideoDevice: newVideoDevice,
currentVideoDevice: newVideoDevice[0],
mainStreamManager: newPublisher,
publisher: newPublisher,
});
}
}
} catch (e) {
} catch (e) {
console.error(e);
}
}
}
render() {
@ -310,79 +310,39 @@ class App extends Component {
);
}
/**
* --------------------------
* SERVER-SIDE RESPONSIBILITY
* --------------------------
* These methods retrieve the mandatory user token from OpenVidu Server.
* This behavior MUST BE IN YOUR SERVER-SIDE IN PRODUCTION (by using
* the API REST, openvidu-java-client or openvidu-node-client):
* 1) Initialize a Session in OpenVidu Server (POST /openvidu/api/sessions)
* 2) Create a Connection in OpenVidu Server (POST /openvidu/api/sessions/<SESSION_ID>/connection)
* 3) The Connection.token must be consumed in Session.connect() method
* --------------------------------------------
* GETTING A TOKEN FROM YOUR APPLICATION SERVER
* --------------------------------------------
* The methods below request the creation of a Session and a Token to
* your application server. This keeps your OpenVidu deployment secure.
*
* In this sample code, there is no user control at all. Anybody could
* access your application server endpoints! In a real production
* environment, your application server must identify the user to allow
* access to the endpoints.
*
* Visit https://docs.openvidu.io/en/stable/application-server to learn
* more about the integration of OpenVidu in your application server.
*/
getToken() {
return this.createSession(this.state.mySessionId).then((sessionId) => this.createToken(sessionId));
async getToken() {
const sessionId = await this.createSession(this.state.mySessionId);
return await this.createToken(sessionId);
}
createSession(sessionId) {
return new Promise((resolve, reject) => {
var data = JSON.stringify({ customSessionId: sessionId });
axios
.post(OPENVIDU_SERVER_URL + '/openvidu/api/sessions', data, {
headers: {
Authorization: 'Basic ' + btoa('OPENVIDUAPP:' + OPENVIDU_SERVER_SECRET),
'Content-Type': 'application/json',
},
})
.then((response) => {
console.log('CREATE SESION', response);
resolve(response.data.id);
})
.catch((response) => {
var error = Object.assign({}, response);
if (error?.response?.status === 409) {
resolve(sessionId);
} else {
console.log(error);
console.warn(
'No connection to OpenVidu Server. This may be a certificate error at ' +
OPENVIDU_SERVER_URL,
);
if (
window.confirm(
'No connection to OpenVidu Server. This may be a certificate error at "' +
OPENVIDU_SERVER_URL +
'"\n\nClick OK to navigate and accept it. ' +
'If no certificate warning is shown, then check that your OpenVidu Server is up and running at "' +
OPENVIDU_SERVER_URL +
'"',
)
) {
window.location.assign(OPENVIDU_SERVER_URL + '/accept-certificate');
}
}
});
async createSession(sessionId) {
const response = await axios.post(APPLICATION_SERVER_URL + 'api/sessions', { customSessionId: sessionId }, {
headers: { 'Content-Type': 'application/json', },
});
return response.data; // The sessionId
}
createToken(sessionId) {
return new Promise((resolve, reject) => {
var data = {};
axios
.post(OPENVIDU_SERVER_URL + "/openvidu/api/sessions/" + sessionId + "/connection", data, {
headers: {
Authorization: 'Basic ' + btoa('OPENVIDUAPP:' + OPENVIDU_SERVER_SECRET),
'Content-Type': 'application/json',
},
})
.then((response) => {
console.log('TOKEN', response);
resolve(response.data.token);
})
.catch((error) => reject(error));
async createToken(sessionId) {
const response = await axios.post(APPLICATION_SERVER_URL + 'api/sessions/' + sessionId + '/connections', {}, {
headers: { 'Content-Type': 'application/json', },
});
return response.data; // The token
}
}

View File

@ -6,9 +6,9 @@
[![][OpenViduLogo]](http://openvidu.io)
openvidu-insecure-vue
openvidu-vue
===
Visit [docs.openvidu.io/en/stable/tutorials/openvidu-insecure-vue/](http://docs.openvidu.io/en/stable/tutorials/openvidu-insecure-vue/)
Visit [docs.openvidu.io/en/stable/tutorials/openvidu-vue/](http://docs.openvidu.io/en/stable/tutorials/openvidu-vue/)
[OpenViduLogo]: https://secure.gravatar.com/avatar/5daba1d43042f2e4e85849733c8e5702?s=120

View File

@ -1,5 +1,5 @@
{
"name": "openvidu-insecure-vue",
"name": "openvidu-vue",
"version": "2.22.0",
"private": true,
"scripts": {

View File

@ -22,9 +22,9 @@
<nav class="navbar navbar-default">
<div class="container">
<div class="navbar-header">
<a class="navbar-brand" href="/"><img class="demo-logo" src="resources/images/openvidu_vert_white_bg_trans_cropped.png"/> Insecure Vue</a>
<a class="navbar-brand nav-icon" href="https://github.com/OpenVidu/openvidu-tutorials/tree/master/openvidu-insecure-vue" 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-insecure-vue/" title="Documentation" target="_blank"><i class="fa fa-book" aria-hidden="true"></i></a>
<a class="navbar-brand" href="/"><img class="demo-logo" src="resources/images/openvidu_vert_white_bg_trans_cropped.png"/> Vue</a>
<a class="navbar-brand nav-icon" href="https://github.com/OpenVidu/openvidu-tutorials/tree/master/openvidu-vue" 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-vue/" title="Documentation" target="_blank"><i class="fa fa-book" aria-hidden="true"></i></a>
</div>
</div>
</nav>

View File

@ -1,213 +1,201 @@
<template>
<div id="main-container" class="container">
<div id="join" v-if="!session">
<div id="img-div"><img src="resources/images/openvidu_grey_bg_transp_cropped.png" /></div>
<div id="join-dialog" class="jumbotron vertical-center">
<h1>Join a video session</h1>
<div class="form-group">
<p>
<label>Participant</label>
<input v-model="myUserName" class="form-control" type="text" required>
</p>
<p>
<label>Session</label>
<input v-model="mySessionId" class="form-control" type="text" required>
</p>
<p class="text-center">
<button class="btn btn-lg btn-success" @click="joinSession()">Join!</button>
</p>
</div>
</div>
</div>
<div id="main-container" class="container">
<div id="join" v-if="!session">
<div id="img-div">
<img src="resources/images/openvidu_grey_bg_transp_cropped.png" />
</div>
<div id="join-dialog" class="jumbotron vertical-center">
<h1>Join a video session</h1>
<div class="form-group">
<p>
<label>Participant</label>
<input v-model="myUserName" class="form-control" type="text" required />
</p>
<p>
<label>Session</label>
<input v-model="mySessionId" class="form-control" type="text" required />
</p>
<p class="text-center">
<button class="btn btn-lg btn-success" @click="joinSession()">
Join!
</button>
</p>
</div>
</div>
</div>
<div id="session" v-if="session">
<div id="session-header">
<h1 id="session-title">{{ mySessionId }}</h1>
<input class="btn btn-large btn-danger" type="button" id="buttonLeaveSession" @click="leaveSession" value="Leave session">
</div>
<div id="main-video" class="col-md-6">
<user-video :stream-manager="mainStreamManager"/>
</div>
<div id="video-container" class="col-md-6">
<user-video :stream-manager="publisher" @click.native="updateMainVideoStreamManager(publisher)"/>
<user-video v-for="sub in subscribers" :key="sub.stream.connection.connectionId" :stream-manager="sub" @click.native="updateMainVideoStreamManager(sub)"/>
</div>
</div>
</div>
<div id="session" v-if="session">
<div id="session-header">
<h1 id="session-title">{{ mySessionId }}</h1>
<input class="btn btn-large btn-danger" type="button" id="buttonLeaveSession" @click="leaveSession"
value="Leave session" />
</div>
<div id="main-video" class="col-md-6">
<user-video :stream-manager="mainStreamManager" />
</div>
<div id="video-container" class="col-md-6">
<user-video :stream-manager="publisher" @click.native="updateMainVideoStreamManager(publisher)" />
<user-video v-for="sub in subscribers" :key="sub.stream.connection.connectionId" :stream-manager="sub"
@click.native="updateMainVideoStreamManager(sub)" />
</div>
</div>
</div>
</template>
<script>
import axios from 'axios';
import { OpenVidu } from 'openvidu-browser';
import UserVideo from './components/UserVideo';
import { OpenVidu } from "openvidu-browser";
import axios from "axios";
import UserVideo from "./components/UserVideo";
axios.defaults.headers.post['Content-Type'] = 'application/json';
axios.defaults.headers.post["Content-Type"] = "application/json";
const OPENVIDU_SERVER_URL = "https://" + location.hostname + ":4443";
const OPENVIDU_SERVER_SECRET = "MY_SECRET";
const APPLICATION_SERVER_URL = window.location.protocol + "//" + window.location.hostname + ":5000/";
export default {
name: 'App',
name: "App",
components: {
UserVideo,
},
components: {
UserVideo,
},
data () {
return {
OV: undefined,
session: undefined,
mainStreamManager: undefined,
publisher: undefined,
subscribers: [],
data() {
return {
// OpenVidu objects
OV: undefined,
session: undefined,
mainStreamManager: undefined,
publisher: undefined,
subscribers: [],
mySessionId: 'SessionA',
myUserName: 'Participant' + Math.floor(Math.random() * 100),
}
},
// Join form
mySessionId: "SessionA",
myUserName: "Participant" + Math.floor(Math.random() * 100),
};
},
methods: {
joinSession () {
// --- Get an OpenVidu object ---
this.OV = new OpenVidu();
methods: {
joinSession() {
// --- 1) Get an OpenVidu object ---
this.OV = new OpenVidu();
// --- Init a session ---
this.session = this.OV.initSession();
// --- 2) Init a session ---
this.session = this.OV.initSession();
// --- Specify the actions when events take place in the session ---
// --- 3) Specify the actions when events take place in the session ---
// On every new Stream received...
this.session.on('streamCreated', ({ stream }) => {
const subscriber = this.session.subscribe(stream);
this.subscribers.push(subscriber);
});
// On every new Stream received...
this.session.on("streamCreated", ({ stream }) => {
const subscriber = this.session.subscribe(stream);
this.subscribers.push(subscriber);
});
// On every Stream destroyed...
this.session.on('streamDestroyed', ({ stream }) => {
const index = this.subscribers.indexOf(stream.streamManager, 0);
if (index >= 0) {
this.subscribers.splice(index, 1);
}
});
// On every Stream destroyed...
this.session.on("streamDestroyed", ({ stream }) => {
const index = this.subscribers.indexOf(stream.streamManager, 0);
if (index >= 0) {
this.subscribers.splice(index, 1);
}
});
// On every asynchronous exception...
this.session.on('exception', ({ exception }) => {
console.warn(exception);
});
// On every asynchronous exception...
this.session.on("exception", ({ exception }) => {
console.warn(exception);
});
// --- Connect to the session with a valid user token ---
// --- 4) Connect to the session with a valid user token ---
// 'getToken' method is simulating what your server-side should do.
// 'token' parameter should be retrieved and returned by your own backend
this.getToken(this.mySessionId).then(token => {
this.session.connect(token, { clientData: this.myUserName })
.then(() => {
// Get a token from the OpenVidu deployment
this.getToken(this.mySessionId).then((token) => {
// --- Get your own camera stream with the desired properties ---
// First param is the token. Second param can be retrieved by every user on event
// 'streamCreated' (property Stream.connection.data), and will be appended to DOM as the user's nickname
this.session.connect(token, { clientData: this.myUserName })
.then(() => {
let publisher = this.OV.initPublisher(undefined, {
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
});
// --- 5) Get your own camera stream with the desired properties ---
this.mainStreamManager = publisher;
this.publisher = publisher;
// Init a publisher passing undefined as targetElement (we don't want OpenVidu to insert a video
// element: we will manage it on our own) and with the desired properties
let publisher = this.OV.initPublisher(undefined, {
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
});
// --- Publish your stream ---
// Set the main video in the page to display our webcam and store our Publisher
this.mainStreamManager = publisher;
this.publisher = publisher;
this.session.publish(this.publisher);
})
.catch(error => {
console.log('There was an error connecting to the session:', error.code, error.message);
});
});
// --- 6) Publish your stream ---
window.addEventListener('beforeunload', this.leaveSession)
},
this.session.publish(this.publisher);
})
.catch((error) => {
console.log("There was an error connecting to the session:", error.code, error.message);
});
});
leaveSession () {
// --- Leave the session by calling 'disconnect' method over the Session object ---
if (this.session) this.session.disconnect();
window.addEventListener("beforeunload", this.leaveSession);
},
this.session = undefined;
this.mainStreamManager = undefined;
this.publisher = undefined;
this.subscribers = [];
this.OV = undefined;
leaveSession() {
// --- 7) Leave the session by calling 'disconnect' method over the Session object ---
if (this.session) this.session.disconnect();
window.removeEventListener('beforeunload', this.leaveSession);
},
// Empty all properties...
this.session = undefined;
this.mainStreamManager = undefined;
this.publisher = undefined;
this.subscribers = [];
this.OV = undefined;
updateMainVideoStreamManager (stream) {
if (this.mainStreamManager === stream) return;
this.mainStreamManager = stream;
},
// Remove beforeunload listener
window.removeEventListener("beforeunload", this.leaveSession);
},
/**
* --------------------------
* SERVER-SIDE RESPONSIBILITY
* --------------------------
* These methods retrieve the mandatory user token from OpenVidu Server.
* This behavior MUST BE IN YOUR SERVER-SIDE IN PRODUCTION (by using
* the API REST, openvidu-java-client or openvidu-node-client):
* 1) Initialize a Session in OpenVidu Server (POST /openvidu/api/sessions)
* 2) Create a Connection in OpenVidu Server (POST /openvidu/api/sessions/<SESSION_ID>/connection)
* 3) The Connection.token must be consumed in Session.connect() method
*/
updateMainVideoStreamManager(stream) {
if (this.mainStreamManager === stream) return;
this.mainStreamManager = stream;
},
getToken (mySessionId) {
return this.createSession(mySessionId).then(sessionId => this.createToken(sessionId));
},
/**
* --------------------------------------------
* GETTING A TOKEN FROM YOUR APPLICATION SERVER
* --------------------------------------------
* The methods below request the creation of a Session and a Token to
* your application server. This keeps your OpenVidu deployment secure.
*
* In this sample code, there is no user control at all. Anybody could
* access your application server endpoints! In a real production
* environment, your application server must identify the user to allow
* access to the endpoints.
*
* Visit https://docs.openvidu.io/en/stable/application-server to learn
* more about the integration of OpenVidu in your application server.
*/
async getToken(mySessionId) {
const sessionId = await this.createSession(mySessionId);
return await this.createToken(sessionId);
},
// See https://docs.openvidu.io/en/stable/reference-docs/REST-API/#post-session
createSession (sessionId) {
return new Promise((resolve, reject) => {
axios
.post(`${OPENVIDU_SERVER_URL}/openvidu/api/sessions`, JSON.stringify({
customSessionId: sessionId,
}), {
auth: {
username: 'OPENVIDUAPP',
password: OPENVIDU_SERVER_SECRET,
},
})
.then(response => response.data)
.then(data => resolve(data.id))
.catch(error => {
if (error.response.status === 409) {
resolve(sessionId);
} else {
console.warn(`No connection to OpenVidu Server. This may be a certificate error at ${OPENVIDU_SERVER_URL}`);
if (window.confirm(`No connection to OpenVidu Server. This may be a certificate error at ${OPENVIDU_SERVER_URL}\n\nClick OK to navigate and accept it. If no certificate warning is shown, then check that your OpenVidu Server is up and running at "${OPENVIDU_SERVER_URL}"`)) {
location.assign(`${OPENVIDU_SERVER_URL}/accept-certificate`);
}
reject(error.response);
}
});
});
},
async createSession(sessionId) {
const response = await axios.post(APPLICATION_SERVER_URL + 'api/sessions', { customSessionId: sessionId }, {
headers: { 'Content-Type': 'application/json', },
});
return response.data; // The sessionId
},
// See https://docs.openvidu.io/en/stable/reference-docs/REST-API/#post-connection
createToken (sessionId) {
return new Promise((resolve, reject) => {
axios
.post(`${OPENVIDU_SERVER_URL}/openvidu/api/sessions/${sessionId}/connection`, {}, {
auth: {
username: 'OPENVIDUAPP',
password: OPENVIDU_SERVER_SECRET,
},
})
.then(response => response.data)
.then(data => resolve(data.token))
.catch(error => reject(error.response));
});
},
}
}
async createToken(sessionId) {
const response = await axios.post(APPLICATION_SERVER_URL + 'api/sessions/' + sessionId + '/connections', {}, {
headers: { 'Content-Type': 'application/json', },
});
return response.data; // The token
},
},
};
</script>

View File

@ -11,9 +11,9 @@ openvidu-internet-explorer
> IE support is a paid feature. Please, contact OpenVidu team through https://openvidu.io/commercial if you are interested
This is an adaptation of [openvidu-insecure-js](https://github.com/OpenVidu/openvidu-tutorials/tree/master/openvidu-insecure-js) application with all necessary changes to work fine on IE 11.
This is an adaptation of [openvidu-js](https://github.com/OpenVidu/openvidu-tutorials/tree/master/openvidu-js) application with all necessary changes to work fine on IE 11.
<!-- Visit [docs.openvidu.io/en/stable/tutorials/openvidu-insecure-js/](http://docs.openvidu.io/en/stable/tutorials/openvidu-insecure-js/) -->
<!-- Visit [docs.openvidu.io/en/stable/tutorials/openvidu-js/](http://docs.openvidu.io/en/stable/tutorials/openvidu-js/) -->
OpenVidu Team has been able to bring complete, standards-compliant WebRTC funcionality to Microsoft Internet Explorer desktop browser (v 11). This feature has been released thanks to [Temasys WebRTC Plugin](https://temasys.io/products/plugin/).

View File

@ -22,13 +22,13 @@ function joinSession() {
// --- 3) Specify the actions when events take place in the session ---
// On every new Stream received...
session.on('streamCreated', function(event) {
session.on('streamCreated', function (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', function (event) {
// Add a new <p> element for the user's nickname just below its video
appendUserData(subscriber, event.element, subscriber.stream.connection);
@ -36,7 +36,7 @@ function joinSession() {
});
// On every Stream destroyed...
session.on('streamDestroyed', function(event) {
session.on('streamDestroyed', function (event) {
// Delete the HTML element with the user's nickname. HTML videos are automatically removed from DOM
removeUserData(event.stream.connection);
@ -45,14 +45,13 @@ function joinSession() {
// --- 4) Connect to the session with a valid user token ---
// 'getToken' method is simulating what your server-side should do.
// 'token' parameter should be retrieved and returned by your own backend
getToken(mySessionId).then(function(token) {
// Get a token from the OpenVidu deployment
getToken(mySessionId).then(function (token) {
// First param is the token got from OpenVidu Server. Second param can be retrieved by every user on event
// First param is the token got from the OpenVidu deployment. Second param can be retrieved by every user on event
// 'streamCreated' (property Stream.connection.data), and will be appended to DOM as the user's nickname
session.connect(token, { clientData: myUserName })
.then(function() {
.then(function () {
// --- 5) Set page layout for active call ---
@ -93,7 +92,7 @@ function joinSession() {
session.publish(publisher);
})
.catch(function(error) {
.catch(function (error) {
console.log('There was an error connecting to the session:', error.code, error.message);
});
});
@ -177,7 +176,7 @@ function addClickListener(streamManager, videoElement, userData) {
differentVideo = mainVideo.srcObject !== videoElement.srcObject
}
if (differentVideo) {
$('#main-video').fadeOut("fast", function() {
$('#main-video').fadeOut("fast", function () {
$('#main-video p').html(userData);
streamManager.addVideoElement(mainVideo);
$('#main-video').fadeIn("fast");
@ -198,28 +197,31 @@ function initMainVideo(publisher, userData) {
}
/**
* --------------------------
* SERVER-SIDE RESPONSIBILITY
* --------------------------
* These methods retrieve the mandatory user token from OpenVidu Server.
* This behavior MUST BE IN YOUR SERVER-SIDE IN PRODUCTION (by using
* the API REST, openvidu-java-client or openvidu-node-client):
* 1) Initialize a Session in OpenVidu Server (POST /openvidu/api/sessions)
* 2) Create a Connection in OpenVidu Server (POST /openvidu/api/sessions/<SESSION_ID>/connection)
* 3) The Connection.token must be consumed in Session.connect() method
* --------------------------------------------
* GETTING A TOKEN FROM YOUR APPLICATION SERVER
* --------------------------------------------
* The methods below request the creation of a Session and a Token to
* your application server. This keeps your OpenVidu deployment secure.
*
* In this sample code, there is no user control at all. Anybody could
* access your application server endpoints! In a real production
* environment, your application server must identify the user to allow
* access to the endpoints.
*
* Visit https://docs.openvidu.io/en/stable/application-server to learn
* more about the integration of OpenVidu in your application server.
*/
var OPENVIDU_SERVER_URL = "https://" + location.hostname + ":4443";
var OPENVIDU_SERVER_SECRET = "MY_SECRET";
function getToken(mySessionId) {
return createSession(mySessionId).then(function(sessionId) { return createToken(sessionId); });
return createSession(mySessionId).then(function (sessionId) { return createToken(sessionId); });
}
function createSession(sessionId) { // See https://docs.openvidu.io/en/stable/reference-docs/REST-API/#post-openviduapisessions
return new Promise(function(resolve, reject) {
return new Promise(function (resolve, reject) {
$.ajax({
type: "POST",
url: OPENVIDU_SERVER_URL + "/openvidu/api/sessions",
@ -228,8 +230,8 @@ function createSession(sessionId) { // See https://docs.openvidu.io/en/stable/re
"Authorization": "Basic " + btoa("OPENVIDUAPP:" + OPENVIDU_SERVER_SECRET),
"Content-Type": "application/json"
},
success: function(response) { resolve(response.id); },
error: function(error) {
success: function (response) { resolve(response.id); },
error: function (error) {
if (error.status === 409) {
resolve(sessionId);
} else {
@ -245,7 +247,7 @@ function createSession(sessionId) { // See https://docs.openvidu.io/en/stable/re
}
function createToken(sessionId) { // See https://docs.openvidu.io/en/stable/reference-docs/REST-API/#post-openviduapisessionsltsession_idgtconnection
return new Promise(function(resolve, reject) {
return new Promise(function (resolve, reject) {
$.ajax({
type: "POST",
url: OPENVIDU_SERVER_URL + "/openvidu/api/sessions/" + sessionId + "/connection",
@ -254,8 +256,8 @@ function createToken(sessionId) { // See https://docs.openvidu.io/en/stable/refe
"Authorization": "Basic " + btoa("OPENVIDUAPP:" + OPENVIDU_SERVER_SECRET),
"Content-Type": "application/json"
},
success: function(response) { resolve(response.token); },
error: function(error) { reject(error); }
success: function (response) { resolve(response.token); },
error: function (error) { reject(error); }
});
});
}

View File

@ -2,7 +2,7 @@
<html>
<head>
<title>openvidu-insecure-js</title>
<title>openvidu-internet-explorer</title>
<meta name="viewport" content="width=device-width, initial-scale=1" charset="utf-8">
<link rel="shortcut icon" href="resources/images/favicon.ico" type="image/x-icon">

View File

@ -1,9 +1,9 @@
import { HttpClient, HttpHeaders } from "@angular/common/http";
import { Component, HostListener, OnDestroy } from "@angular/core";
import { AndroidPermissions } from "@ionic-native/android-permissions/ngx";
import { SplashScreen } from "@ionic-native/splash-screen/ngx";
import { StatusBar } from "@ionic-native/status-bar/ngx";
import { Platform, AlertController } from "@ionic/angular";
import { HttpClient } from '@angular/common/http';
import { Component, HostListener, OnDestroy } from '@angular/core';
import { AndroidPermissions } from '@ionic-native/android-permissions/ngx';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';
import { AlertController, Platform } from '@ionic/angular';
import {
Device,
OpenVidu,
@ -12,24 +12,22 @@ import {
Session,
StreamEvent,
StreamManager,
Subscriber,
} from "openvidu-browser";
import { throwError as observableThrowError } from "rxjs";
import { catchError } from "rxjs/operators";
Subscriber
} from 'openvidu-browser';
@Component({
selector: "app-root",
templateUrl: "app.component.html",
styleUrls: ["app.component.css"],
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.css']
})
export class AppComponent implements OnDestroy {
OPENVIDU_SERVER_URL = "https://" + location.hostname + ":4443";
OPENVIDU_SERVER_SECRET = "MY_SECRET";
APPLICATION_SERVER_URL = location.protocol + '//' + location.hostname + ':5000/';
ANDROID_PERMISSIONS = [
this.androidPermissions.PERMISSION.CAMERA,
this.androidPermissions.PERMISSION.RECORD_AUDIO,
this.androidPermissions.PERMISSION.MODIFY_AUDIO_SETTINGS,
this.androidPermissions.PERMISSION.MODIFY_AUDIO_SETTINGS
];
// OpenVidu objects
@ -42,23 +40,23 @@ export class AppComponent implements OnDestroy {
mySessionId: string;
myUserName: string;
cameraIcon = "videocam";
microphoneIcon = "mic";
cameraIcon = 'videocam';
microphoneIcon = 'mic';
private devices: Device[];
private cameras: Device[];
private microphones: Device[];
private cameraSelected: Device;
private microphoneSelected: Device;
private isFrontCamera: boolean = false;
private isFrontCamera: boolean = false;
constructor(
private httpClient: HttpClient,
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private httpClient: HttpClient,
private androidPermissions: AndroidPermissions,
public alertController: AlertController
private alertController: AlertController
) {
this.initializeApp();
this.generateParticipantInfo();
@ -71,7 +69,7 @@ export class AppComponent implements OnDestroy {
});
}
@HostListener("window:beforeunload")
@HostListener('window:beforeunload')
beforeunloadHandler() {
// On window closed leave session
this.leaveSession();
@ -94,57 +92,49 @@ export class AppComponent implements OnDestroy {
// --- 3) Specify the actions when events take place in the session ---
// On every new Stream received...
this.session.on("streamCreated", (event: StreamEvent) => {
this.session.on('streamCreated', (event: StreamEvent) => {
// Subscribe to the Stream to receive it. Second parameter is undefined
// so OpenVidu doesn't create an HTML video on its own
const subscriber: Subscriber = this.session.subscribe(
event.stream,
undefined
);
const subscriber: Subscriber = this.session.subscribe(event.stream, undefined);
this.subscribers.push(subscriber);
});
// On every Stream destroyed...
this.session.on("streamDestroyed", (event: StreamEvent) => {
this.session.on('streamDestroyed', (event: StreamEvent) => {
// Remove the stream from 'subscribers' array
this.deleteSubscriber(event.stream.streamManager);
});
// On every asynchronous exception...
this.session.on("exception", (exception) => {
this.session.on('exception', (exception) => {
console.warn(exception);
});
// --- 4) Connect to the session with a valid user token ---
try {
// 'getToken' method is simulating what your server-side should do.
// 'token' parameter should be retrieved and returned by your own backend
// Get a token from the OpenVidu deployment
const token = await this.getToken();
// First param is the token got from OpenVidu Server. Second param will be used by every user on event
// First param is the token got from OpenVidu deployment. Second param will be used by every user on event
// 'streamCreated' (property Stream.connection.data), and will be appended to DOM as the user's nickname
await this.session.connect(token, { clientData: this.myUserName });
// --- 5) Requesting and Checking Android Permissions
if (this.platform.is("cordova")) {
if (this.platform.is('cordova')) {
// Ionic platform
if (this.platform.is("android")) {
console.log("Android platform");
if (this.platform.is('android')) {
console.log('Android platform');
await this.checkAndroidPermissions();
this.initPublisher();
} else if (this.platform.is("ios")) {
console.log("iOS platform");
} else if (this.platform.is('ios')) {
console.log('iOS platform');
this.initPublisher();
}
} else {
this.initPublisher();
}
} catch (error) {
console.log(
"There was an error connecting to the session:",
error.code,
error.message
);
console.log('There was an error connecting to the session:', error.code, error.message);
}
}
@ -156,10 +146,10 @@ export class AppComponent implements OnDestroy {
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
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: this.isFrontCamera, // Whether to mirror your local video or not
insertMode: 'APPEND', // How the video is inserted in the target element 'video-container'
mirror: this.isFrontCamera // Whether to mirror your local video or not
});
publisher.on('accessAllowed', () => this.initDevices());
@ -188,11 +178,8 @@ export class AppComponent implements OnDestroy {
async swapCamera() {
try {
const newCamera = this.cameras.find(
(cam) => cam.deviceId !== this.cameraSelected.deviceId
);
const newCamera = this.cameras.find(cam => cam.deviceId !== this.cameraSelected.deviceId);
if (!!newCamera) {
this.isFrontCamera = !this.isFrontCamera;
const pp: PublisherProperties = {
videoSource: newCamera.deviceId,
@ -206,7 +193,7 @@ export class AppComponent implements OnDestroy {
const newTrack = await this.OV.getUserMedia(pp);
const videoTrack: MediaStreamTrack = newTrack.getVideoTracks()[0];
await (this.publisher as Publisher).replaceTrack(videoTrack);
this.cameraSelected = newCamera;
this.cameraSelected = newCamera;
}
} catch (error) {
console.error(error);
@ -215,106 +202,49 @@ export class AppComponent implements OnDestroy {
toggleCamera() {
const publish = !this.publisher.stream.videoActive;
(this.publisher as Publisher).publishVideo(publish, true);
this.cameraIcon = publish ? "videocam" : "eye-off";
this.cameraIcon = publish ? 'videocam' : 'eye-off';
}
toggleMicrophone() {
const publish = !this.publisher.stream.audioActive;
(this.publisher as Publisher).publishAudio(publish);
this.microphoneIcon = publish ? "mic" : "mic-off";
this.microphoneIcon = publish ? 'mic' : 'mic-off';
}
private async initDevices() {
this.devices = await this.OV.getDevices();
this.cameras = this.devices.filter((d) => d.kind === "videoinput");
this.microphones = this.devices.filter(
(d) => d.kind === "audioinput" && d.label !== "Default"
);
this.cameras = this.devices.filter(d => d.kind === 'videoinput');
this.microphones = this.devices.filter(d => d.kind === 'audioinput' && d.label !== 'Default');
this.cameraSelected = this.cameras[0];
this.microphoneSelected = this.microphones[0];
}
private checkAndroidPermissions(): Promise<void> {
return new Promise((resolve, reject) => {
this.platform.ready().then(() => {
this.androidPermissions
.requestPermissions(this.ANDROID_PERMISSIONS)
.then(() => {
this.androidPermissions
.checkPermission(this.androidPermissions.PERMISSION.CAMERA)
.then((camera) => {
this.androidPermissions
.checkPermission(
this.androidPermissions.PERMISSION.RECORD_AUDIO
)
.then((audio) => {
this.androidPermissions
.checkPermission(
this.androidPermissions.PERMISSION.MODIFY_AUDIO_SETTINGS
)
.then((modifyAudio) => {
if (
camera.hasPermission &&
audio.hasPermission &&
modifyAudio.hasPermission
) {
resolve();
} else {
reject(
new Error(
"Permissions denied: " +
"\n" +
" CAMERA = " +
camera.hasPermission +
"\n" +
" AUDIO = " +
audio.hasPermission +
"\n" +
" AUDIO_SETTINGS = " +
modifyAudio.hasPermission
)
);
}
})
.catch((err) => {
console.error(
"Checking permission " +
this.androidPermissions.PERMISSION
.MODIFY_AUDIO_SETTINGS +
" failed"
);
reject(err);
});
})
.catch((err) => {
console.error(
"Checking permission " +
this.androidPermissions.PERMISSION.RECORD_AUDIO +
" failed"
);
reject(err);
});
})
.catch((err) => {
console.error(
"Checking permission " +
this.androidPermissions.PERMISSION.CAMERA +
" failed"
);
reject(err);
});
})
.catch((err) => console.error("Error requesting permissions: ", err));
});
});
private async checkAndroidPermissions(): Promise<void> {
await this.platform.ready();
try {
await this.androidPermissions.requestPermissions(this.ANDROID_PERMISSIONS);
const camera = await this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.CAMERA);
const audio = await this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.RECORD_AUDIO);
const modifyAudio = await this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.MODIFY_AUDIO_SETTINGS);
if (!camera.hasPermission || !audio.hasPermission || !modifyAudio.hasPermission) {
throw new Error('Permissions denied: \n CAMERA = ' + camera.hasPermission +
'\n AUDIO = ' + audio.hasPermission +
'\n AUDIO_SETTINGS = ' + modifyAudio.hasPermission
);
}
} catch (error) {
console.error('Error requesting or checking permissions: ', error);
throw (error);
}
}
private generateParticipantInfo() {
// Random user nickname and sessionId
this.mySessionId = "SessionA";
this.myUserName = "Participant" + Math.floor(Math.random() * 100);
this.mySessionId = 'SessionA';
this.myUserName = 'Participant' + Math.floor(Math.random() * 100);
}
private deleteSubscriber(streamManager: StreamManager): void {
@ -326,32 +256,25 @@ export class AppComponent implements OnDestroy {
async presentSettingsAlert() {
const alert = await this.alertController.create({
header: "OpenVidu Server config",
header: 'OpenVidu deployment',
inputs: [
{
name: "url",
type: "text",
value: "https://demos.openvidu.io",
placeholder: "URL",
},
{
name: "secret",
type: "text",
value: "MY_SECRET",
placeholder: "Secret",
},
name: 'url',
type: 'text',
value: 'https://demos.openvidu.io/',
placeholder: 'URL',
}
],
buttons: [
{
text: "Cancel",
role: "cancel",
cssClass: "secondary",
text: 'Cancel',
role: 'cancel',
cssClass: 'secondary',
},
{
text: "Ok",
text: 'Ok',
handler: (data) => {
this.OPENVIDU_SERVER_URL = data.url;
this.OPENVIDU_SERVER_SECRET = data.secret;
this.APPLICATION_SERVER_URL = data.url;
},
},
],
@ -360,112 +283,48 @@ export class AppComponent implements OnDestroy {
await alert.present();
}
/*
* --------------------------
* SERVER-SIDE RESPONSIBILITY
* --------------------------
* This method retrieve the mandatory user token from OpenVidu Server,
* in this case making use Angular http API.
* This behaviour MUST BE IN YOUR SERVER-SIDE IN PRODUCTION. In this case:
* 1) Initialize a Session in OpenVidu Server (POST /openvidu/api/sessions)
* 2) Create a Connection in OpenVidu Server (POST /openvidu/api/sessions/<SESSION_ID>/connection)
* 3) The Connection.token must be consumed in Session.connect() method
*/
getToken(): Promise<string> {
/**
* --------------------------------------------
* GETTING A TOKEN FROM YOUR APPLICATION SERVER
* --------------------------------------------
* The methods below request the creation of a Session and a Token to
* your application server. This keeps your OpenVidu deployment secure.
*
* In this sample code, there is no user control at all. Anybody could
* access your application server endpoints! In a real production
* environment, your application server must identify the user to allow
* access to the endpoints.
*
* Visit https://docs.openvidu.io/en/stable/application-server to learn
* more about the integration of OpenVidu in your application server.
*/
async getToken(): Promise<string> {
if (
this.platform.is("ios") &&
this.platform.is("cordova") &&
this.OPENVIDU_SERVER_URL === "https://localhost:4443"
this.platform.is('ios') &&
this.platform.is('cordova') &&
this.APPLICATION_SERVER_URL === 'http://localhost:5000/'
) {
// To make easier first steps with iOS apps, use demos OpenVidu Sever if no custom valid server is configured
this.OPENVIDU_SERVER_URL = "https://demos.openvidu.io";
// To make easier first steps with iOS apps, use demos OpenVidu deployment when no custom deployment is configured
this.APPLICATION_SERVER_URL = 'https://demos.openvidu.io/';
}
return this.createSession(this.mySessionId).then((sessionId) => {
return this.createToken(sessionId);
});
const sessionId = await this.createSession(this.mySessionId);
return await this.createToken(sessionId);
}
createSession(sessionId) {
return new Promise((resolve, reject) => {
const body = JSON.stringify({ customSessionId: sessionId });
const options = {
headers: new HttpHeaders({
Authorization:
"Basic " + btoa("OPENVIDUAPP:" + this.OPENVIDU_SERVER_SECRET),
"Content-Type": "application/json",
}),
};
return this.httpClient
.post(
this.OPENVIDU_SERVER_URL + "/openvidu/api/sessions",
body,
options
)
.pipe(
catchError((error) => {
if (error.status === 409) {
resolve(sessionId);
} else {
console.warn(
"No connection to OpenVidu Server. This may be a certificate error at " +
this.OPENVIDU_SERVER_URL
);
if (
window.confirm(
'No connection to OpenVidu Server. This may be a certificate error at "' +
this.OPENVIDU_SERVER_URL +
// tslint:disable-next-line:max-line-length
'"\n\nClick OK to navigate and accept it. If no certificate warning is shown, then check that your OpenVidu Server' +
'is up and running at "' +
this.OPENVIDU_SERVER_URL +
'"'
)
) {
location.assign(
this.OPENVIDU_SERVER_URL + "/accept-certificate"
);
}
}
return observableThrowError(error);
})
)
.subscribe((response) => {
console.log(response);
resolve(response["id"]);
});
});
return this.httpClient.post(
this.APPLICATION_SERVER_URL + 'api/sessions',
{ customSessionId: sessionId },
{ headers: { 'Content-Type': 'application/json' }, responseType: 'text' }
).toPromise();
}
createToken(sessionId): Promise<string> {
return new Promise((resolve, reject) => {
const body = JSON.stringify({});
const options = {
headers: new HttpHeaders({
Authorization:
"Basic " + btoa("OPENVIDUAPP:" + this.OPENVIDU_SERVER_SECRET),
"Content-Type": "application/json",
}),
};
return this.httpClient
.post(
this.OPENVIDU_SERVER_URL +
"/openvidu/api/sessions/" +
sessionId +
"/connection",
body,
options
)
.pipe(
catchError((error) => {
reject(error);
return observableThrowError(error);
})
)
.subscribe((response) => {
console.log(response);
resolve(response["token"]);
});
});
createToken(sessionId) {
return this.httpClient.post(
this.APPLICATION_SERVER_URL + 'api/sessions/' + sessionId + '/connections',
{ customSessionId: sessionId },
{ headers: { 'Content-Type': 'application/json' }, responseType: 'text' }
).toPromise();
}
}

View File

@ -12,10 +12,11 @@ import { StreamManager } from "openvidu-browser";
template: '<video #videoElement style="width: 100%"></video>',
})
export class OpenViduVideoComponent implements AfterViewInit {
@ViewChild("videoElement") elementRef: ElementRef;
_streamManager: StreamManager;
constructor() {}
constructor() { }
ngAfterViewInit() {
this.updateVideoView();

View File

@ -1,13 +1,11 @@
import React, { Component } from 'react';
import { Platform, TextInput, ScrollView, Button, Alert, Linking, StyleSheet, Text, View, Image, PermissionsAndroid } from 'react-native';
import { Platform, TextInput, ScrollView, Button, StyleSheet, Text, View, Image, PermissionsAndroid } from 'react-native';
import InCallManager from 'react-native-incall-manager';
import axios from 'axios';
import { OpenViduReactNativeAdapter, OpenVidu, RTCView } from 'openvidu-react-native-adapter';
const OPENVIDU_SERVER_URL = 'https://demos.openvidu.io';
const OPENVIDU_SERVER_SECRET = 'MY_SECRET';
const APPLICATION_SERVER_URL = 'https://demos.openvidu.io/';
type Props = {};
export default class App extends Component<Props> {
@ -101,9 +99,10 @@ export default class App extends Component<Props> {
role,
},
async () => {
const mySession = this.state.session;
// --- 3) Specify the actions when events take place in the session ---
const mySession = this.state.session;
// On every new Stream received...
mySession.on('streamCreated', async (event) => {
// Subscribe to the Stream to receive it. Second parameter is undefined
@ -142,6 +141,7 @@ export default class App extends Component<Props> {
this.setState({ isReconnecting: false });
}, 2000);
});
mySession.on('sessionDisconnected', (event) => {
if (event.reason === 'networkDisconnect') {
console.warn('Dang-it... You lost your connection to the session');
@ -153,10 +153,9 @@ export default class App extends Component<Props> {
try {
// --- 4) Connect to the session with a valid user token ---
// 'getToken' method is simulating what your server-side should do.
// 'token' parameter should be retrieved and returned by your own backend
// Get a token from the OpenVidu deployment
const token = await this.getToken();
// First param is the token got from OpenVidu Server. Second param can be retrieved by every user on event
// First param is the token got from the OpenVidu deployment. Second param can be retrieved by every user on event
// 'streamCreated' (property Stream.connection.data), and will be appended to DOM as the user's nickname
await mySession.connect(token, { clientData: this.state.myUserName });
@ -166,7 +165,11 @@ export default class App extends Component<Props> {
// --- 5) Get your own camera stream ---
if (this.state.role !== 'SUBSCRIBER') {
const properties = {
// Init a publisher passing undefined as targetElement (we don't want OpenVidu to insert a video
// element: we will manage it on our own) and with the desired properties
const publisher = await this.OV.initPublisherAsync(undefined, {
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
@ -174,24 +177,17 @@ export default class App extends Component<Props> {
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'
};
});
// Init a publisher passing undefined as targetElement (we don't want OpenVidu to insert a video
// element: we will manage it on our own) and with the desired propertiesç
const publisher = await this.OV.initPublisherAsync(undefined, properties);
// --- 6) Publish your stream ---
// Set the main video in the page to display our webcam and store our Publisher
this.setState(
{
mainStreamManager: publisher,
videoSource: !properties.videoSource ? '1' : properties.videoSource, // 0: back camera | 1: user camera |
},
() => {
mySession.publish(publisher);
},
);
this.setState({
mainStreamManager: publisher,
videoSource: !properties.videoSource ? '1' : properties.videoSource, // 0: back camera | 1: user camera |
}, () => {
mySession.publish(publisher);
});
}
this.setState({ connected: true });
} catch (error) {
@ -210,7 +206,7 @@ export default class App extends Component<Props> {
if (stream.connection && JSON.parse(stream.connection.data) && JSON.parse(stream.connection.data).clientData) {
return JSON.parse(stream.connection.data).clientData;
}
} catch (error) {}
} catch (error) { }
return '';
}
@ -267,31 +263,31 @@ export default class App extends Component<Props> {
* Renegotiating stream and init new publisher to change the camera
*/
/*
this.OV.getDevices().then(devices => {
console.log("DEVICES => ", devices);
let device = devices.filter(device => device.kind === 'videoinput' && device.deviceId !== this.state.videoSource)[0]
const properties = {
audioSource: undefined,
videoSource: device.deviceId,
publishAudio: true,
publishVideo: true,
resolution: '640x480',
frameRate: 30,
insertMode: 'APPEND',
}
this.OV.getDevices().then(devices => {
console.log("DEVICES => ", devices);
let device = devices.filter(device => device.kind === 'videoinput' && device.deviceId !== this.state.videoSource)[0]
const properties = {
audioSource: undefined,
videoSource: device.deviceId,
publishAudio: true,
publishVideo: true,
resolution: '640x480',
frameRate: 30,
insertMode: 'APPEND',
}
let publisher = this.OV.initPublisher(undefined, properties);
let publisher = this.OV.initPublisher(undefined, properties);
this.state.session.unpublish(this.state.mainStreamManager);
this.state.session.unpublish(this.state.mainStreamManager);
this.setState({
videoSource : device.deviceId,
mainStreamManager: publisher,
mirror: !this.state.mirror
});
this.state.session.publish(publisher);
});
*/
this.setState({
videoSource : device.deviceId,
mainStreamManager: publisher,
mirror: !this.state.mirror
});
this.state.session.publish(publisher);
});
*/
}
muteUnmuteMic() {
@ -436,101 +432,39 @@ export default class App extends Component<Props> {
);
}
/**
* --------------------------
* SERVER-SIDE RESPONSIBILITY
* --------------------------
* These methods retrieve the mandatory user token from OpenVidu Server.
* This behavior MUST BE IN YOUR SERVER-SIDE IN PRODUCTION (by using
* the API REST, openvidu-java-client or openvidu-node-client):
* 1) Initialize a Session in OpenVidu Server (POST /openvidu/api/sessions)
* 2) Create a Connection in OpenVidu Server (POST /openvidu/api/sessions/<SESSION_ID>/connection)
* 3) The Connection.token must be consumed in Session.connect() method
* --------------------------------------------
* GETTING A TOKEN FROM YOUR APPLICATION SERVER
* --------------------------------------------
* The methods below request the creation of a Session and a Token to
* your application server. This keeps your OpenVidu deployment secure.
*
* In this sample code, there is no user control at all. Anybody could
* access your application server endpoints! In a real production
* environment, your application server must identify the user to allow
* access to the endpoints.
*
* Visit https://docs.openvidu.io/en/stable/application-server to learn
* more about the integration of OpenVidu in your application server.
*/
getToken() {
return this.createSession(this.state.mySessionId)
.then((sessionId) => this.createToken(sessionId))
.catch((error) => console.log(error));
async getToken() {
const sessionId = await this.createSession(this.state.mySessionId);
return await this.createToken(sessionId);
}
createSession(sessionId) {
return new Promise((resolve) => {
var data = JSON.stringify({ customSessionId: sessionId });
axios
.post(OPENVIDU_SERVER_URL + '/openvidu/api/sessions', data, {
headers: {
Authorization: 'Basic ' + btoa('OPENVIDUAPP:' + OPENVIDU_SERVER_SECRET),
'Content-Type': 'application/json',
Accept: 'application/json',
},
})
.then((response) => {
console.log('SESSION ' + response.data.id + ' CREATED');
resolve(response.data.id);
})
.catch((response) => {
console.log(response);
var error = Object.assign({}, response);
if (!error.response) {
console.error('Network error: ', error);
if (error.request && error.request._response) {
console.error('Response of the request: ', error.request._response);
}
} else if (error.response && error.response.status && error.response.status === 409) {
console.log('RESOLVING WITH SESSIONID, 409');
resolve(sessionId);
} else {
console.warn('No connection to OpenVidu Server. This may be a certificate error at ' + OPENVIDU_SERVER_URL);
Alert.alert(
'No connection to OpenVidu Server.',
'This may be a certificate error at "' +
OPENVIDU_SERVER_URL +
'"\n\nClick OK to navigate and accept it. ' +
'If no certificate warning is shown, then check that your OpenVidu Server is up and running at "' +
OPENVIDU_SERVER_URL +
'"',
[
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel',
},
{
text: 'OK',
onPress: () =>
Linking.openURL(OPENVIDU_SERVER_URL + '/accept-certificate').catch((err) =>
console.error('An error occurred', err),
),
},
],
{ cancelable: false },
);
}
});
async createSession(sessionId) {
const response = await axios.post(APPLICATION_SERVER_URL + 'api/sessions', { customSessionId: sessionId }, {
headers: { 'Content-Type': 'application/json', },
});
return response.data; // The sessionId
}
createToken(sessionId) {
return new Promise((resolve, reject) => {
var data = JSON.stringify({ role: this.state.role });
axios
.post(OPENVIDU_SERVER_URL + '/openvidu/api/sessions/' + sessionId + '/connection', data, {
headers: {
Authorization: 'Basic ' + btoa('OPENVIDUAPP:' + OPENVIDU_SERVER_SECRET),
'Content-Type': 'application/json',
},
})
.then((response) => {
console.log('TOKEN CREATED: ', response.data.token);
resolve(response.data.token);
})
.catch((error) => {
console.error(error);
reject(error);
});
async createToken(sessionId) {
const response = await axios.post(APPLICATION_SERVER_URL + 'api/sessions/' + sessionId + '/connections', {}, {
headers: { 'Content-Type': 'application/json', },
});
return response.data; // The token
}
}

View File

@ -52,51 +52,54 @@ function joinSession() {
// --- 4) Connect to the session with a valid user token ---
// 'getToken' method is simulating what your server-side should do.
// 'token' parameter should be retrieved and returned by your own backend
// Get a token from the OpenVidu deployment
getToken(mySessionId).then(token => {
// First param is the token got from OpenVidu Server. Second param can be retrieved by every user on event
// First param is the token got from the OpenVidu deployment. Second param can be retrieved by every user on event
// 'streamCreated' (property Stream.connection.data), and will be appended to DOM as the user's nickname
session.connect(token, { clientData: myUserName })
.then(() => {
// --- 5) Set page layout for active call ---
$("#session-title").text(mySessionId);
$("#join").hide();
$("#session").show();
document.getElementById('session-title').innerText = mySessionId;
document.getElementById('join').style.display = 'none';
document.getElementById('session').style.display = 'block';
// --- 6) Get your own camera stream with the desired properties ---
var publisherProperties = {
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: "640x360", // The resolution of your video
framerate: 24,
mirror: true, // Whether to mirror your local video or not
};
publisher = OV.initPublisher("video-container", publisherProperties);
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: 24, // The frame rate of your video
insertMode: 'APPEND', // How the video is inserted in the target element 'video-container'
mirror: true // 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 => {
appendUserData(event.element, publisher);
initMainVideo(publisher, myUserName);
publisher.on('videoElementCreated', function (event) {
initMainVideo(event.element, myUserName);
appendUserData(event.element, myUserName);
event.element['muted'] = true;
});
// When our video has started playing...
publisher.on("streamPlaying", event => {
$("#spinner-" + publisher.stream.connection.connectionId).remove();
$("#virtual-background-btns").show();
publisher.on('streamPlaying', event => {
$('#spinner-' + publisher.stream.connection.connectionId).remove();
$('#virtual-background-btns').show();
});
// --- 8) Publish your stream ---
session.publish(publisher);
})
.catch(error => {
console.log("There was an error connecting to the session:", error.code, error.message);
console.log('There was an error connecting to the session:', error.code, error.message);
});
});
}
@ -195,10 +198,10 @@ function appendUserData(videoElement, streamManager) {
// Insert user nickname
var dataNode = $(
'<div id="data-' +
nodeId +
'" class="data-node"><p>' +
userData +
"</p></div>"
nodeId +
'" class="data-node"><p>' +
userData +
"</p></div>"
);
dataNode.insertAfter($(videoElement));
// Insert spinner loader
@ -278,79 +281,49 @@ function imageVirtualBackgroundButtons() {
/**
* --------------------------
* SERVER-SIDE RESPONSIBILITY
* --------------------------
* These methods retrieve the mandatory user token from OpenVidu Server.
* This behavior MUST BE IN YOUR SERVER-SIDE IN PRODUCTION (by using
* the REST API, openvidu-java-client or openvidu-node-client):
* 1) Initialize a Session in OpenVidu Server (POST /openvidu/api/sessions)
* 2) Create a Connection in OpenVidu Server (POST /openvidu/api/sessions/<SESSION_ID>/connection)
* 3) The Connection.token must be consumed in Session.connect() method
* --------------------------------------------
* GETTING A TOKEN FROM YOUR APPLICATION SERVER
* --------------------------------------------
* The methods below request the creation of a Session and a Token to
* your application server. This keeps your OpenVidu deployment secure.
*
* In this sample code, there is no user control at all. Anybody could
* access your application server endpoints! In a real production
* environment, your application server must identify the user to allow
* access to the endpoints.
*
* Visit https://docs.openvidu.io/en/stable/application-server to learn
* more about the integration of OpenVidu in your application server.
*/
var OPENVIDU_SERVER_URL = "https://" + location.hostname + ":4443";
var OPENVIDU_SERVER_SECRET = "MY_SECRET";
var APPLICATION_SERVER_URL = window.location.protocol + "//" + window.location.hostname + ":5000/";
function getToken(mySessionId) {
return createSession(mySessionId).then((sessionId) => createToken(sessionId));
return createSession(mySessionId).then(sessionId => createToken(sessionId));
}
function createSession(sessionId) {
// See https://docs.openvidu.io/en/stable/reference-docs/REST-API/#post-openviduapisessions
return new Promise((resolve, reject) => {
$.ajax({
type: "POST",
url: OPENVIDU_SERVER_URL + "/openvidu/api/sessions",
url: APPLICATION_SERVER_URL + "api/sessions",
data: JSON.stringify({ customSessionId: sessionId }),
headers: {
Authorization: "Basic " + btoa("OPENVIDUAPP:" + OPENVIDU_SERVER_SECRET),
"Content-Type": "application/json",
},
success: (response) => resolve(response.id),
error: (error) => {
if (error.status === 409) {
resolve(sessionId);
} else {
console.warn(
"No connection to OpenVidu Server. This may be a certificate error at " +
OPENVIDU_SERVER_URL
);
if (
window.confirm(
'No connection to OpenVidu Server. This may be a certificate error at "' +
OPENVIDU_SERVER_URL +
'"\n\nClick OK to navigate and accept it. ' +
'If no certificate warning is shown, then check that your OpenVidu Server is up and running at "' +
OPENVIDU_SERVER_URL +
'"'
)
) {
location.assign(OPENVIDU_SERVER_URL + "/accept-certificate");
}
}
},
headers: { "Content-Type": "application/json" },
success: response => resolve(response), // The sessionId
error: (error) => reject(error)
});
});
}
function createToken(sessionId) {
// See https://docs.openvidu.io/en/stable/reference-docs/REST-API/#post-openviduapisessionsltsession_idgtconnection
return new Promise((resolve, reject) => {
$.ajax({
type: "POST",
url:
OPENVIDU_SERVER_URL +
"/openvidu/api/sessions/" +
sessionId +
"/connection",
type: 'POST',
url: APPLICATION_SERVER_URL + 'api/sessions/' + sessionId + '/connections',
data: JSON.stringify({}),
headers: {
Authorization: "Basic " + btoa("OPENVIDUAPP:" + OPENVIDU_SERVER_SECRET),
"Content-Type": "application/json",
},
success: (response) => resolve(response.token),
error: (error) => reject(error),
headers: { "Content-Type": "application/json" },
success: (response) => resolve(response), // The token
error: (error) => reject(error)
});
});
}
}

View File

@ -1,5 +1,5 @@
$(document).ready(async() => {
$(document).ready(async () => {
var webComponent = document.querySelector('openvidu-webcomponent');
var form = document.getElementById('main');
@ -32,15 +32,15 @@ $(document).ready(async() => {
});
});
webComponent.addEventListener('onJoinButtonClicked', (event) => {});
webComponent.addEventListener('onToolbarLeaveButtonClicked', (event) => {});
webComponent.addEventListener('onToolbarCameraButtonClicked', (event) => {});
webComponent.addEventListener('onToolbarMicrophoneButtonClicked', (event) => {});
webComponent.addEventListener('onToolbarScreenshareButtonClicked', (event) => {});
webComponent.addEventListener('onToolbarParticipantsPanelButtonClicked', (event) => {});
webComponent.addEventListener('onToolbarChatPanelButtonClicked', (event) => {});
webComponent.addEventListener('onToolbarFullscreenButtonClicked', (event) => {});
webComponent.addEventListener('onParticipantCreated', (event) => {});
webComponent.addEventListener('onJoinButtonClicked', (event) => { });
webComponent.addEventListener('onToolbarLeaveButtonClicked', (event) => { });
webComponent.addEventListener('onToolbarCameraButtonClicked', (event) => { });
webComponent.addEventListener('onToolbarMicrophoneButtonClicked', (event) => { });
webComponent.addEventListener('onToolbarScreenshareButtonClicked', (event) => { });
webComponent.addEventListener('onToolbarParticipantsPanelButtonClicked', (event) => { });
webComponent.addEventListener('onToolbarChatPanelButtonClicked', (event) => { });
webComponent.addEventListener('onToolbarFullscreenButtonClicked', (event) => { });
webComponent.addEventListener('onParticipantCreated', (event) => { });
});
@ -51,7 +51,7 @@ async function joinSession() {
// Requesting tokens
var promiseResults = await Promise.all([getToken(sessionName), getToken(sessionName)]);
var tokens = {webcam: promiseResults[0], screen: promiseResults[1]};
var tokens = { webcam: promiseResults[0], screen: promiseResults[1] };
//Getting the webcomponent element
var webComponent = document.querySelector('openvidu-webcomponent');
@ -75,15 +75,15 @@ async function joinSession() {
// webComponent.toolbarScreenshareButton = true;
// webComponent.toolbarFullscreenButton = true;
// webComponent.toolbarLeaveButton = true;
// webComponent.toolbarChatPanelButton = true;
// webComponent.toolbarParticipantsPanelButton = true;
// webComponent.toolbarDisplayLogo = true;
// webComponent.toolbarDisplaySessionName = true;
// webComponent.streamDisplayParticipantName = true;
// webComponent.streamDisplayAudioDetection = true;
// webComponent.streamSettingsButton = true;
// webComponent.participantPanelItemMuteButton = true;
// webComponent.toolbarLeaveButton = true;
// webComponent.toolbarChatPanelButton = true;
// webComponent.toolbarParticipantsPanelButton = true;
// webComponent.toolbarDisplayLogo = true;
// webComponent.toolbarDisplaySessionName = true;
// webComponent.streamDisplayParticipantName = true;
// webComponent.streamDisplayAudioDetection = true;
// webComponent.streamSettingsButton = true;
// webComponent.participantPanelItemMuteButton = true;
webComponent.tokens = tokens;
}
@ -94,71 +94,51 @@ function hideForm() {
}
/**
* --------------------------
* SERVER-SIDE RESPONSIBILITY
* --------------------------
* These methods retrieve the mandatory user token from OpenVidu Server.
* This behavior MUST BE IN YOUR SERVER-SIDE IN PRODUCTION (by using
* the API REST, openvidu-java-client or openvidu-node-client):
* 1) Initialize a Session in OpenVidu Server (POST /openvidu/api/sessions)
* 2) Create a Connection in OpenVidu Server (POST /openvidu/api/sessions/<SESSION_ID>/connection)
* 3) The Connection.token must be consumed in Session.connect() method
* --------------------------------------------
* GETTING A TOKEN FROM YOUR APPLICATION SERVER
* --------------------------------------------
* The methods below request the creation of a Session and a Token to
* your application server. This keeps your OpenVidu deployment secure.
*
* In this sample code, there is no user control at all. Anybody could
* access your application server endpoints! In a real production
* environment, your application server must identify the user to allow
* access to the endpoints.
*
* Visit https://docs.openvidu.io/en/stable/application-server to learn
* more about the integration of OpenVidu in your application server.
*/
var OPENVIDU_SERVER_URL = "https://localhost:4443";
var OPENVIDU_SERVER_SECRET = 'MY_SECRET';
var APPLICATION_SERVER_URL = window.location.protocol + "//" + window.location.hostname + ":5000/";
function getToken(sessionName) {
return createSession(sessionName).then((sessionId) => createToken(sessionId));
function getToken(mySessionId) {
return createSession(mySessionId).then(sessionId => createToken(sessionId));
}
function createSession(sessionName) { // See https://docs.openvidu.io/en/stable/reference-docs/REST-API/#post-openviduapisessions
function createSession(sessionId) {
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: OPENVIDU_SERVER_URL + '/openvidu/api/sessions',
data: JSON.stringify({ customSessionId: sessionName }),
headers: {
Authorization: 'Basic ' + btoa('OPENVIDUAPP:' + OPENVIDU_SERVER_SECRET),
'Content-Type': 'application/json',
},
success: (response) => resolve(response.id),
error: (error) => {
if (error.status === 409) {
resolve(sessionName);
} else {
console.warn('No connection to OpenVidu Server. This may be a certificate error at ' + OPENVIDU_SERVER_URL);
if (
window.confirm(
'No connection to OpenVidu Server. This may be a certificate error at "' +
OPENVIDU_SERVER_URL +
'"\n\nClick OK to navigate and accept it. ' +
'If no certificate warning is shown, then check that your OpenVidu Server is up and running at "' +
OPENVIDU_SERVER_URL +
'"',
)
) {
location.assign(OPENVIDU_SERVER_URL + '/accept-certificate');
}
}
},
});
});
}
function createToken(sessionId) { // See https://docs.openvidu.io/en/stable/reference-docs/REST-API/#post-openviduapisessionsltsession_idgtconnection
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: OPENVIDU_SERVER_URL + '/openvidu/api/sessions/' + sessionId + '/connection',
data: JSON.stringify({}),
headers: {
'Authorization': 'Basic ' + btoa('OPENVIDUAPP:' + OPENVIDU_SERVER_SECRET),
'Content-Type': 'application/json',
},
success: (response) => resolve(response.token),
type: "POST",
url: APPLICATION_SERVER_URL + "api/sessions",
data: JSON.stringify({ customSessionId: sessionId }),
headers: { "Content-Type": "application/json" },
success: response => resolve(response), // The sessionId
error: (error) => reject(error)
});
});
}
function createToken(sessionId) {
return new Promise((resolve, reject) => {
$.ajax({
type: 'POST',
url: APPLICATION_SERVER_URL + 'api/sessions/' + sessionId + '/connections',
data: JSON.stringify({}),
headers: { "Content-Type": "application/json" },
success: (response) => resolve(response), // The token
error: (error) => reject(error)
});
});
}

View File

@ -32,8 +32,8 @@ if [[ ! -z "$FROM_VERSION_SDK" || ! -z "$TO_VERSION_SDK" ]]; then
fi
echo
NPM_TUTORIALS="openvidu-insecure-angular
openvidu-insecure-react
NPM_TUTORIALS="openvidu-angular
openvidu-react
openvidu-library-react
openvidu-ionic
openvidu-js-node
@ -41,7 +41,7 @@ NPM_TUTORIALS="openvidu-insecure-angular
openvidu-recording-node
openvidu-react-native
openvidu-electron
openvidu-insecure-vue
openvidu-vue
openvidu-call/openvidu-call-front
openvidu-call/openvidu-call-back"
@ -54,7 +54,7 @@ MAVEN_TUTORIALS="openvidu-js-java
find -type f -name 'package-lock.json' -exec rm {} \;
find -type d -name 'node_modules' -prune -exec rm -rf {} \;
# Updating openvidu-browser dependencies in package.json files [openvidu-insecure-angular, openvidu-insecure-react, openvidu-ionic, openvidu-insecure-vue]
# Updating openvidu-browser dependencies in package.json files [openvidu-angular, openvidu-react, openvidu-ionic, openvidu-vue]
find . -type f -name 'package.json' -exec sed -i "s/\"openvidu-browser\": \"$FROM_VERSION\"/\"openvidu-browser\": \"$TO_VERSION\"/" {} \;
# Updating openvidu-react dependencies in package.json files [openvidu-library-react]