From b74e2060238615208ab2d108fd947c775407e3ea Mon Sep 17 00:00:00 2001 From: pabloFuente Date: Mon, 8 Aug 2022 19:35:46 +0200 Subject: [PATCH] Update all tutorials to use a server application --- docker/openvidu-basic-screenshare/Dockerfile | 2 +- .../openvidu-basic-videoconference/Dockerfile | 2 +- openvidu-filters/web/app.js | 28 +- openvidu-getaroom/web/app.js | 52 +-- openvidu-hark-events/web/app.js | 24 +- openvidu-hello-world/web/app.js | 75 ++-- openvidu-insecure-angular/README.md | 4 +- openvidu-insecure-angular/angular.json | 16 +- .../e2e/src/app.e2e-spec.ts | 2 +- openvidu-insecure-angular/karma.conf.js | 2 +- openvidu-insecure-angular/package.json | 2 +- .../src/app/app.component.ts | 106 ++---- openvidu-insecure-angular/src/index.html | 8 +- openvidu-insecure-js-screen-share/README.md | 4 +- .../docker/Dockerfile | 8 +- .../docker/create_image.sh | 4 +- .../docker/docker-compose.override.yml | 5 +- .../docker/entrypoint.sh | 4 +- .../openvidu-insecure-js-screen-share.conf | 2 +- openvidu-insecure-js-screen-share/web/app.js | 131 +++---- .../web/index.html | 8 +- openvidu-insecure-js/README.md | 4 +- openvidu-insecure-js/docker/Dockerfile | 8 +- openvidu-insecure-js/docker/create_image.sh | 4 +- .../docker/docker-compose.override.yml | 5 +- openvidu-insecure-js/docker/entrypoint.sh | 4 +- .../docker/openvidu-insecure-js.conf | 2 +- openvidu-insecure-js/web/app.js | 86 ++--- openvidu-insecure-js/web/index.html | 8 +- openvidu-insecure-react/README.md | 4 +- openvidu-insecure-react/package.json | 2 +- openvidu-insecure-react/public/index.html | 8 +- openvidu-insecure-react/src/App.js | 136 +++---- openvidu-insecure-vue/README.md | 4 +- openvidu-insecure-vue/package.json | 2 +- openvidu-insecure-vue/public/index.html | 6 +- openvidu-insecure-vue/src/App.vue | 344 ++++++++--------- openvidu-internet-explorer/README.md | 4 +- openvidu-internet-explorer/web/app.js | 56 +-- openvidu-internet-explorer/web/index.html | 2 +- openvidu-ionic/src/app/app.component.ts | 353 ++++++------------ openvidu-ionic/src/app/ov-video.component.ts | 3 +- openvidu-react-native/App.js | 200 ++++------ openvidu-virtual-background/web/app.js | 135 +++---- openvidu-webcomponent/web/app.js | 132 +++---- update-tutorials.sh | 8 +- 46 files changed, 813 insertions(+), 1196 deletions(-) diff --git a/docker/openvidu-basic-screenshare/Dockerfile b/docker/openvidu-basic-screenshare/Dockerfile index 4a802a9d..cf3f39f9 100644 --- a/docker/openvidu-basic-screenshare/Dockerfile +++ b/docker/openvidu-basic-screenshare/Dockerfile @@ -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 diff --git a/docker/openvidu-basic-videoconference/Dockerfile b/docker/openvidu-basic-videoconference/Dockerfile index ccc31b9a..c7a2cecf 100644 --- a/docker/openvidu-basic-videoconference/Dockerfile +++ b/docker/openvidu-basic-videoconference/Dockerfile @@ -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 diff --git a/openvidu-filters/web/app.js b/openvidu-filters/web/app.js index 8c53f0ff..5bb3b47c 100644 --- a/openvidu-filters/web/app.js +++ b/openvidu-filters/web/app.js @@ -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//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"; diff --git a/openvidu-getaroom/web/app.js b/openvidu-getaroom/web/app.js index 9f288206..15a0ad05 100644 --- a/openvidu-getaroom/web/app.js +++ b/openvidu-getaroom/web/app.js @@ -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//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) + }); + }); } \ No newline at end of file diff --git a/openvidu-hark-events/web/app.js b/openvidu-hark-events/web/app.js index ac722da4..a61b9d12 100644 --- a/openvidu-hark-events/web/app.js +++ b/openvidu-hark-events/web/app.js @@ -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//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'); } } diff --git a/openvidu-hello-world/web/app.js b/openvidu-hello-world/web/app.js index c2e75ac6..41b09671 100644 --- a/openvidu-hello-world/web/app.js +++ b/openvidu-hello-world/web/app.js @@ -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//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) + }); + }); } \ No newline at end of file diff --git a/openvidu-insecure-angular/README.md b/openvidu-insecure-angular/README.md index f651a9f8..a04172d1 100644 --- a/openvidu-insecure-angular/README.md +++ b/openvidu-insecure-angular/README.md @@ -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 \ No newline at end of file diff --git a/openvidu-insecure-angular/angular.json b/openvidu-insecure-angular/angular.json index a53a3f50..2fa38500 100644 --- a/openvidu-insecure-angular/angular.json +++ b/openvidu-insecure-angular/angular.json @@ -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" } diff --git a/openvidu-insecure-angular/e2e/src/app.e2e-spec.ts b/openvidu-insecure-angular/e2e/src/app.e2e-spec.ts index 02252dbc..04b5dfa9 100644 --- a/openvidu-insecure-angular/e2e/src/app.e2e-spec.ts +++ b/openvidu-insecure-angular/e2e/src/app.e2e-spec.ts @@ -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 () => { diff --git a/openvidu-insecure-angular/karma.conf.js b/openvidu-insecure-angular/karma.conf.js index 1d628fcc..65753d98 100644 --- a/openvidu-insecure-angular/karma.conf.js +++ b/openvidu-insecure-angular/karma.conf.js @@ -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 }, diff --git a/openvidu-insecure-angular/package.json b/openvidu-insecure-angular/package.json index 56c372de..e790cb2c 100644 --- a/openvidu-insecure-angular/package.json +++ b/openvidu-insecure-angular/package.json @@ -1,5 +1,5 @@ { - "name": "openvidu-insecure-angular", + "name": "openvidu-angular", "version": "2.22.0", "license": "Apache-2.0", "scripts": { diff --git a/openvidu-insecure-angular/src/app/app.component.ts b/openvidu-insecure-angular/src/app/app.component.ts index ea326fdc..63aa2572 100644 --- a/openvidu-insecure-angular/src/app/app.component.ts +++ b/openvidu-insecure-angular/src/app/app.component.ts @@ -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//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 { - return this.createSession(this.mySessionId).then( - sessionId => { - return this.createToken(sessionId); - }) + async getToken(): Promise { + 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 { - 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(); } } diff --git a/openvidu-insecure-angular/src/index.html b/openvidu-insecure-angular/src/index.html index 0522a1c1..fdec2b55 100644 --- a/openvidu-insecure-angular/src/index.html +++ b/openvidu-insecure-angular/src/index.html @@ -2,7 +2,7 @@ - openvidu-insecure-angular + openvidu-angular @@ -21,9 +21,9 @@ diff --git a/openvidu-insecure-js-screen-share/README.md b/openvidu-insecure-js-screen-share/README.md index b668044b..bfc48190 100644 --- a/openvidu-insecure-js-screen-share/README.md +++ b/openvidu-insecure-js-screen-share/README.md @@ -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 diff --git a/openvidu-insecure-js-screen-share/docker/Dockerfile b/openvidu-insecure-js-screen-share/docker/Dockerfile index 8bc35182..1ad6a940 100644 --- a/openvidu-insecure-js-screen-share/docker/Dockerfile +++ b/openvidu-insecure-js-screen-share/docker/Dockerfile @@ -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 diff --git a/openvidu-insecure-js-screen-share/docker/create_image.sh b/openvidu-insecure-js-screen-share/docker/create_image.sh index 821496ea..80d37b7f 100755 --- a/openvidu-insecure-js-screen-share/docker/create_image.sh +++ b/openvidu-insecure-js-screen-share/docker/create_image.sh @@ -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 diff --git a/openvidu-insecure-js-screen-share/docker/docker-compose.override.yml b/openvidu-insecure-js-screen-share/docker/docker-compose.override.yml index b021da84..5d543bd5 100644 --- a/openvidu-insecure-js-screen-share/docker/docker-compose.override.yml +++ b/openvidu-insecure-js-screen-share/docker/docker-compose.override.yml @@ -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} \ No newline at end of file diff --git a/openvidu-insecure-js-screen-share/docker/entrypoint.sh b/openvidu-insecure-js-screen-share/docker/entrypoint.sh index e17e3f67..f9e7184c 100644 --- a/openvidu-insecure-js-screen-share/docker/entrypoint.sh +++ b/openvidu-insecure-js-screen-share/docker/entrypoint.sh @@ -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 diff --git a/openvidu-insecure-js-screen-share/docker/openvidu-insecure-js-screen-share.conf b/openvidu-insecure-js-screen-share/docker/openvidu-insecure-js-screen-share.conf index 3401a73d..8648257c 100644 --- a/openvidu-insecure-js-screen-share/docker/openvidu-insecure-js-screen-share.conf +++ b/openvidu-insecure-js-screen-share/docker/openvidu-insecure-js-screen-share.conf @@ -1,5 +1,5 @@ server { listen 5442; - root /var/www/openvidu-insecure-js-screen-share; + root /var/www/openvidu-js-screen-share; } diff --git a/openvidu-insecure-js-screen-share/web/app.js b/openvidu-insecure-js-screen-share/web/app.js index be8c0b89..35b2283d 100644 --- a/openvidu-insecure-js-screen-share/web/app.js +++ b/openvidu-insecure-js-screen-share/web/app.js @@ -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//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) + }); + }); + } \ No newline at end of file diff --git a/openvidu-insecure-js-screen-share/web/index.html b/openvidu-insecure-js-screen-share/web/index.html index e6326c1b..6a2c8369 100644 --- a/openvidu-insecure-js-screen-share/web/index.html +++ b/openvidu-insecure-js-screen-share/web/index.html @@ -1,7 +1,7 @@ - openvidu-insecure-js-screen-share + openvidu-js-screen-share @@ -23,9 +23,9 @@ diff --git a/openvidu-insecure-js/README.md b/openvidu-insecure-js/README.md index 603316cd..97472892 100644 --- a/openvidu-insecure-js/README.md +++ b/openvidu-insecure-js/README.md @@ -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 \ No newline at end of file diff --git a/openvidu-insecure-js/docker/Dockerfile b/openvidu-insecure-js/docker/Dockerfile index 53f957fd..9f497707 100644 --- a/openvidu-insecure-js/docker/Dockerfile +++ b/openvidu-insecure-js/docker/Dockerfile @@ -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 diff --git a/openvidu-insecure-js/docker/create_image.sh b/openvidu-insecure-js/docker/create_image.sh index 66cc11df..635fed01 100755 --- a/openvidu-insecure-js/docker/create_image.sh +++ b/openvidu-insecure-js/docker/create_image.sh @@ -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 \ No newline at end of file +docker build -f docker/Dockerfile -t openvidu/openvidu-js-demo . +docker tag openvidu/openvidu-js-demo:latest openvidu/openvidu-js-demo:2.18.0 \ No newline at end of file diff --git a/openvidu-insecure-js/docker/docker-compose.override.yml b/openvidu-insecure-js/docker/docker-compose.override.yml index 597818d0..499b0392 100644 --- a/openvidu-insecure-js/docker/docker-compose.override.yml +++ b/openvidu-insecure-js/docker/docker-compose.override.yml @@ -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} diff --git a/openvidu-insecure-js/docker/entrypoint.sh b/openvidu-insecure-js/docker/entrypoint.sh index 3349ec66..14852a3d 100644 --- a/openvidu-insecure-js/docker/entrypoint.sh +++ b/openvidu-insecure-js/docker/entrypoint.sh @@ -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 diff --git a/openvidu-insecure-js/docker/openvidu-insecure-js.conf b/openvidu-insecure-js/docker/openvidu-insecure-js.conf index d9e1beb1..8e0d3e6a 100644 --- a/openvidu-insecure-js/docker/openvidu-insecure-js.conf +++ b/openvidu-insecure-js/docker/openvidu-insecure-js.conf @@ -1,5 +1,5 @@ server { listen 5442; - root /var/www/openvidu-insecure-js; + root /var/www/openvidu-js; } \ No newline at end of file diff --git a/openvidu-insecure-js/web/app.js b/openvidu-insecure-js/web/app.js index 08bf6bc8..4b01cb55 100644 --- a/openvidu-insecure-js/web/app.js +++ b/openvidu-insecure-js/web/app.js @@ -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//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) + }); + }); } \ No newline at end of file diff --git a/openvidu-insecure-js/web/index.html b/openvidu-insecure-js/web/index.html index 4698b880..c1db85ba 100644 --- a/openvidu-insecure-js/web/index.html +++ b/openvidu-insecure-js/web/index.html @@ -1,7 +1,7 @@ - openvidu-insecure-js + openvidu-js @@ -23,9 +23,9 @@ diff --git a/openvidu-insecure-react/README.md b/openvidu-insecure-react/README.md index 800eafe8..fcdf9c57 100644 --- a/openvidu-insecure-react/README.md +++ b/openvidu-insecure-react/README.md @@ -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 \ No newline at end of file diff --git a/openvidu-insecure-react/package.json b/openvidu-insecure-react/package.json index bad8225d..1f58fe45 100644 --- a/openvidu-insecure-react/package.json +++ b/openvidu-insecure-react/package.json @@ -1,5 +1,5 @@ { - "name": "openvidu-insecure-react", + "name": "openvidu-react", "version": "2.22.0", "private": true, "dependencies": { diff --git a/openvidu-insecure-react/public/index.html b/openvidu-insecure-react/public/index.html index d59fdc4e..808ff254 100644 --- a/openvidu-insecure-react/public/index.html +++ b/openvidu-insecure-react/public/index.html @@ -31,7 +31,7 @@ crossorigin="anonymous"> - openvidu-insecure-react App + openvidu-react App @@ -42,11 +42,11 @@
diff --git a/openvidu-insecure-react/src/App.js b/openvidu-insecure-react/src/App.js index 7929ba1e..13fcca6a 100644 --- a/openvidu-insecure-react/src/App.js +++ b/openvidu-insecure-react/src/App.js @@ -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//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 } } diff --git a/openvidu-insecure-vue/README.md b/openvidu-insecure-vue/README.md index 283f3a58..a4219dc4 100644 --- a/openvidu-insecure-vue/README.md +++ b/openvidu-insecure-vue/README.md @@ -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 \ No newline at end of file diff --git a/openvidu-insecure-vue/package.json b/openvidu-insecure-vue/package.json index 8fe71531..f77dc41f 100644 --- a/openvidu-insecure-vue/package.json +++ b/openvidu-insecure-vue/package.json @@ -1,5 +1,5 @@ { - "name": "openvidu-insecure-vue", + "name": "openvidu-vue", "version": "2.22.0", "private": true, "scripts": { diff --git a/openvidu-insecure-vue/public/index.html b/openvidu-insecure-vue/public/index.html index 46471c9a..1cd8a513 100644 --- a/openvidu-insecure-vue/public/index.html +++ b/openvidu-insecure-vue/public/index.html @@ -22,9 +22,9 @@ diff --git a/openvidu-insecure-vue/src/App.vue b/openvidu-insecure-vue/src/App.vue index 76c06d21..3e14372f 100644 --- a/openvidu-insecure-vue/src/App.vue +++ b/openvidu-insecure-vue/src/App.vue @@ -1,213 +1,201 @@ diff --git a/openvidu-internet-explorer/README.md b/openvidu-internet-explorer/README.md index 97898360..047eb343 100644 --- a/openvidu-internet-explorer/README.md +++ b/openvidu-internet-explorer/README.md @@ -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. - + 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/). diff --git a/openvidu-internet-explorer/web/app.js b/openvidu-internet-explorer/web/app.js index a79967eb..eead4318 100644 --- a/openvidu-internet-explorer/web/app.js +++ b/openvidu-internet-explorer/web/app.js @@ -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

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//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); } }); }); } \ No newline at end of file diff --git a/openvidu-internet-explorer/web/index.html b/openvidu-internet-explorer/web/index.html index 6f977c58..d279234c 100644 --- a/openvidu-internet-explorer/web/index.html +++ b/openvidu-internet-explorer/web/index.html @@ -2,7 +2,7 @@ - openvidu-insecure-js + openvidu-internet-explorer diff --git a/openvidu-ionic/src/app/app.component.ts b/openvidu-ionic/src/app/app.component.ts index d1be4240..3c1203de 100644 --- a/openvidu-ionic/src/app/app.component.ts +++ b/openvidu-ionic/src/app/app.component.ts @@ -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 { - 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 { + 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//connection) - * 3) The Connection.token must be consumed in Session.connect() method - */ - getToken(): Promise { + /** + * -------------------------------------------- + * 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 { 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 { - 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(); } } diff --git a/openvidu-ionic/src/app/ov-video.component.ts b/openvidu-ionic/src/app/ov-video.component.ts index abacdce5..9f9f1b3c 100644 --- a/openvidu-ionic/src/app/ov-video.component.ts +++ b/openvidu-ionic/src/app/ov-video.component.ts @@ -12,10 +12,11 @@ import { StreamManager } from "openvidu-browser"; template: '', }) export class OpenViduVideoComponent implements AfterViewInit { + @ViewChild("videoElement") elementRef: ElementRef; _streamManager: StreamManager; - constructor() {} + constructor() { } ngAfterViewInit() { this.updateVideoView(); diff --git a/openvidu-react-native/App.js b/openvidu-react-native/App.js index c0b33d5f..4cb9b4d7 100644 --- a/openvidu-react-native/App.js +++ b/openvidu-react-native/App.js @@ -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 { @@ -101,9 +99,10 @@ export default class App extends Component { 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 { 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 { 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 { // --- 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 { 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 { 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 { * 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 { ); } + /** - * -------------------------- - * 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//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 } } diff --git a/openvidu-virtual-background/web/app.js b/openvidu-virtual-background/web/app.js index 86f655f9..2002774b 100644 --- a/openvidu-virtual-background/web/app.js +++ b/openvidu-virtual-background/web/app.js @@ -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 = $( '

' + - userData + - "

" + nodeId + + '" class="data-node">

' + + userData + + "

" ); 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//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) }); }); -} +} \ No newline at end of file diff --git a/openvidu-webcomponent/web/app.js b/openvidu-webcomponent/web/app.js index c5d16681..d0bde143 100644 --- a/openvidu-webcomponent/web/app.js +++ b/openvidu-webcomponent/web/app.js @@ -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//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) + }); + }); +} \ No newline at end of file diff --git a/update-tutorials.sh b/update-tutorials.sh index c80a2642..dd195950 100755 --- a/update-tutorials.sh +++ b/update-tutorials.sh @@ -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]