diff --git a/openvidu-js-java/.classpath b/openvidu-js-java/.classpath index 6d7587a8..a5d95095 100644 --- a/openvidu-js-java/.classpath +++ b/openvidu-js-java/.classpath @@ -15,6 +15,7 @@ + diff --git a/openvidu-js-java/pom.xml b/openvidu-js-java/pom.xml index 0b978e7e..9c262d27 100644 --- a/openvidu-js-java/pom.xml +++ b/openvidu-js-java/pom.xml @@ -95,7 +95,7 @@ io.openvidu openvidu-java-client - 1.7.0 + 2.0.0 diff --git a/openvidu-js-java/src/main/java/io/openvidu/js/java/SessionController.java b/openvidu-js-java/src/main/java/io/openvidu/js/java/SessionController.java index a5e9daf3..1617f1c2 100644 --- a/openvidu-js-java/src/main/java/io/openvidu/js/java/SessionController.java +++ b/openvidu-js-java/src/main/java/io/openvidu/js/java/SessionController.java @@ -25,10 +25,10 @@ import io.openvidu.java.client.OpenViduRole; @RequestMapping("/api-sessions") public class SessionController { - OpenVidu openVidu; + private OpenVidu openVidu; private Map mapSessions = new ConcurrentHashMap<>(); - private Map> mapSessionIdsTokens = new ConcurrentHashMap<>(); + private Map> mapSessionNamesTokens = new ConcurrentHashMap<>(); private String OPENVIDU_URL; private String SECRET; @@ -39,8 +39,8 @@ public class SessionController { this.openVidu = new OpenVidu(OPENVIDU_URL, SECRET); } - @RequestMapping(value = "/get-sessionid-token", method = RequestMethod.POST) - public ResponseEntity getSessionIdToken(@RequestBody String sessionNameParam, HttpSession httpSession) + @RequestMapping(value = "/get-token", method = RequestMethod.POST) + public ResponseEntity getToken(@RequestBody String sessionNameParam, HttpSession httpSession) throws ParseException { try { @@ -48,12 +48,12 @@ public class SessionController { } catch (Exception e) { return getErrorResponse(e); } - System.out.println("Getting sessionId and token | {sessionName}=" + sessionNameParam); + System.out.println("Getting a token from OpenVidu Server | {sessionName}=" + sessionNameParam); JSONObject sessionJSON = (JSONObject) new JSONParser().parse(sessionNameParam); // The video-call to connect ("TUTORIAL") - String sessionName = (String) sessionJSON.get("session"); + String sessionName = (String) sessionJSON.get("sessionName"); // Role associated to this user OpenViduRole role = LoginController.users.get(httpSession.getAttribute("loggedUser")).role; @@ -68,22 +68,18 @@ public class SessionController { JSONObject responseJson = new JSONObject(); if (this.mapSessions.get(sessionName) != null) { - // Session already exists: return existing sessionId and a new token + // Session already exists System.out.println("Existing session " + sessionName); try { - // Get the existing sessionId from our collection with - // the sessionName param ("TUTORIAL") - String sessionId = this.mapSessions.get(sessionName).getSessionId(); // Generate a new token with the recently created tokenOptions String token = this.mapSessions.get(sessionName).generateToken(tokenOptions); // Update our collection storing the new token - this.mapSessionIdsTokens.get(sessionId).put(token, role); + this.mapSessionNamesTokens.get(sessionName).put(token, role); - // Prepare the response with the sessionId and the token - responseJson.put(0, sessionId); - responseJson.put(1, token); + // Prepare the response with the token + responseJson.put(0, token); // Return the response to the client return new ResponseEntity<>(responseJson, HttpStatus.OK); @@ -94,25 +90,22 @@ public class SessionController { } } else { - // New session: return a new sessionId and token + // New session System.out.println("New session " + sessionName); try { // Create a new OpenVidu Session Session session = this.openVidu.createSession(); - // Get the sessionId - String sessionId = session.getSessionId(); // Generate a new token with the recently created tokenOptions String token = session.generateToken(tokenOptions); // Store the session and the token in our collections this.mapSessions.put(sessionName, session); - this.mapSessionIdsTokens.put(sessionId, new ConcurrentHashMap<>()); - this.mapSessionIdsTokens.get(sessionId).put(token, role); + this.mapSessionNamesTokens.put(sessionName, new ConcurrentHashMap<>()); + this.mapSessionNamesTokens.get(sessionName).put(token, role); - // Prepare the response with the sessionId and the token - responseJson.put(0, sessionId); - responseJson.put(1, token); + // Prepare the response with the token + responseJson.put(0, token); // Return the response to the client return new ResponseEntity<>(responseJson, HttpStatus.OK); @@ -141,28 +134,22 @@ public class SessionController { String token = (String) sessionNameTokenJSON.get("token"); // If the session exists ("TUTORIAL" in this case) - if (this.mapSessions.get(sessionName) != null) { - String sessionId = this.mapSessions.get(sessionName).getSessionId(); - - if (this.mapSessionIdsTokens.containsKey(sessionId)) { - // If the token exists - if (this.mapSessionIdsTokens.get(sessionId).remove(token) != null) { - // User left the session - if (this.mapSessionIdsTokens.get(sessionId).isEmpty()) { - // Last user left: session must be removed - this.mapSessions.remove(sessionName); - } - return new ResponseEntity<>(HttpStatus.OK); - } else { - // The TOKEN wasn't valid - System.out.println("Problems in the app server: the TOKEN wasn't valid"); - return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); + if (this.mapSessions.get(sessionName) != null && this.mapSessionNamesTokens.get(sessionName) != null) { + + // If the token exists + if (this.mapSessionNamesTokens.get(sessionName).remove(token) != null) { + // User left the session + if (this.mapSessionNamesTokens.get(sessionName).isEmpty()) { + // Last user left: session must be removed + this.mapSessions.remove(sessionName); } + return new ResponseEntity<>(HttpStatus.OK); } else { - // The SESSIONID wasn't valid - System.out.println("Problems in the app server: the SESSIONID wasn't valid"); + // The TOKEN wasn't valid + System.out.println("Problems in the app server: the TOKEN wasn't valid"); return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR); } + } else { // The SESSION does not exist System.out.println("Problems in the app server: the SESSION does not exist"); diff --git a/openvidu-js-java/src/main/resources/application.properties b/openvidu-js-java/src/main/resources/application.properties index a5cec57d..2463c1ef 100644 --- a/openvidu-js-java/src/main/resources/application.properties +++ b/openvidu-js-java/src/main/resources/application.properties @@ -5,5 +5,5 @@ server.ssl.key-store-password: openvidu server.ssl.key-store-type: JKS server.ssl.key-alias: openvidu-selfsigned -openvidu.url: https://localhost:8443/ +openvidu.url: https://localhost:4443/ openvidu.secret: MY_SECRET diff --git a/openvidu-js-java/src/main/resources/static/app.js b/openvidu-js-java/src/main/resources/static/app.js index 6133c478..1386cbca 100644 --- a/openvidu-js-java/src/main/resources/static/app.js +++ b/openvidu-js-java/src/main/resources/static/app.js @@ -1,35 +1,34 @@ var OV; var session; -var sessionId; -var token; -var nickName; -var userName; -var sessionName; +var sessionName; // Name of the video session the user will connect to +var token; // Token retrieved from OpenVidu Server /* OPENVIDU METHODS */ function joinSession() { - getSessionIdAndToken(function () { + getToken((token) => { - // --- 1) Get an OpenVidu object and init a session with the retrieved sessionId --- + // --- 1) Get an OpenVidu object --- OV = new OpenVidu(); - session = OV.initSession(sessionId); + // --- 2) Init a session --- - // --- 2) Specify the actions when events take place --- + session = OV.initSession(); + + // --- 3) Specify the actions when events take place in the session --- // On every new Stream received... - session.on('streamCreated', function (event) { + session.on('streamCreated', (event) => { // Subscribe to the Stream to receive it // HTML video will be appended to element with 'video-container' id var subscriber = session.subscribe(event.stream, 'video-container'); // When the HTML video has been appended to DOM... - subscriber.on('videoElementCreated', function (event) { + subscriber.on('videoElementCreated', (event) => { // Add a new HTML element for the user's name and nickname over its video appendUserData(event.element, subscriber.stream.connection); @@ -37,38 +36,48 @@ function joinSession() { }); // On every Stream destroyed... - session.on('streamDestroyed', function (event) { + session.on('streamDestroyed', (event) => { // Delete the HTML element with the user's name and nickname removeUserData(event.stream.connection); }); - // --- 3) Connect to the session passing the retrieved token and some more data from - // the client (in this case a JSON with the nickname chosen by the user) --- + // --- 4) Connect to the session passing the retrieved token and some more data from + // the client (in this case a JSON with the nickname chosen by the user) --- - session.connect(token, '{"clientData": "' + nickName + '"}', function (error) { + session.connect(token, { clientData: nickName }) + .then(() => { - // If the connection is successful, initialize a publisher and publish to the session - if (!error) { + // --- 5) Set page layout for active call --- - // Here we check somehow if the user has at least 'PUBLISHER' role before + var userName = $("#user").val(); + $('#session-title').text(sessionName); + $('#join').hide(); + $('#session').show(); + + + // Here we check somehow if the user has 'PUBLISHER' role before // trying to publish its stream. Even if someone modified the client's code and // published the stream, it wouldn't work if the token sent in Session.connect - // method doesn't belong to a 'PUBLIHSER' role - if (isPublisher()) { + // method is not recognized as 'PUBLIHSER' role by OpenVidu Server + if (isPublisher(userName)) { - // --- 4) Get your own camera stream --- + // --- 6) Get your own camera stream --- var publisher = OV.initPublisher('video-container', { - audio: true, // Whether you want to transmit audio or not - video: true, // Whether you want to transmit video or not - audioActive: true, // Whether you want to start the publishing with your audio unmuted or muted - videoActive: true, // Whether you want to start the publishing with your video enabled or disabled - quality: 'MEDIUM', // The quality of your video ('LOW', 'MEDIUM', 'HIGH') - screen: false // true to get your screen as video source instead of your camera + audioSource: undefined, // The source of audio. If undefined default microphone + videoSource: undefined, // The source of video. If undefined default webcam + publishAudio: true, // Whether you want to start publishing with your audio unmuted or not + publishVideo: true, // Whether you want to start publishing with your video enabled or not + resolution: '640x480', // The resolution of your video + frameRate: 30, // The frame rate of your video + insertMode: 'APPEND', // How the video is inserted in the target element 'video-container' + mirror: false // Whether to mirror your local video or not }); + // --- 7) Specify the actions when events take place in our publisher --- + // When our HTML video has been added to DOM... - publisher.on('videoElementCreated', function (event) { + publisher.on('videoElementCreated', (event) => { // Init the main video with ours and append our data var userData = { nickName: nickName, @@ -80,7 +89,7 @@ function joinSession() { }); - // --- 5) Publish your stream --- + // --- 8) Publish your stream --- session.publish(publisher); @@ -88,22 +97,18 @@ function joinSession() { console.warn('You don\'t have permissions to publish'); initMainVideoThumbnail(); // Show SUBSCRIBER message in main video } - } else { + }) + .catch(error => { console.warn('There was an error connecting to the session:', error.code, error.message); - } - }); - - $('#session-title').text(sessionName); - $('#join').hide(); - $('#session').show(); - - return false; + }); }); + + return false; } function leaveSession() { - // 6) Leave the session by calling 'disconnect' method over the Session object + // 9) Leave the session by calling 'disconnect' method over the Session object session.disconnect(); session = null; @@ -124,60 +129,63 @@ function leaveSession() { function logIn() { var user = $("#user").val(); // Username var pass = $("#pass").val(); // Password - var jsonBody = JSON.stringify({ // Body of POST request - 'user': user, - 'pass': pass - }); - userName = user; - - httpRequest('POST', 'api-login/login', jsonBody, 'Login WRONG', function successCallback(response) { - console.warn(userName + ' login'); - $("#name-user").text(user); - $("#not-logged").hide(); - $("#logged").show(); - // Random nickName and session - $("#sessionName").val("Session " + Math.floor(Math.random() * 10)); - $("#participantName").val("Participant " + Math.floor(Math.random() * 100)); - }); + httpRequest( + 'POST', + 'api-login/login', + {user: user, pass: pass}, + 'Login WRONG', + (response) => { + $("#name-user").text(user); + $("#not-logged").hide(); + $("#logged").show(); + // Random nickName and session + $("#sessionName").val("Session " + Math.floor(Math.random() * 10)); + $("#nickName").val("Participant " + Math.floor(Math.random() * 100)); + } + ); } function logOut() { - httpRequest('GET', 'api-login/logout', null, 'Logout WRONG', function successCallback(response) { - console.warn(userName + ' logout'); - $("#not-logged").show(); - $("#logged").hide(); - }); + httpRequest( + 'GET', + 'api-login/logout', + null, + 'Logout WRONG', + (response) => { + $("#not-logged").show(); + $("#logged").hide(); + } + ); } -function getSessionIdAndToken(callback) { +function getToken(callback) { sessionName = $("#sessionName").val(); // Video-call chosen by the user - nickName = $("#participantName").val(); // Nickname chosen by the user - - var jsonBody = JSON.stringify({ // Body of POST request - 'session': sessionName - }); + nickName = $("#nickName").val(); // Nickname chosen by the user - // Send POST request - httpRequest('POST', 'api-sessions/get-sessionid-token', jsonBody, 'Request of SESSIONID and TOKEN gone WRONG:', function successCallback(response) { - sessionId = response[0]; // Get sessionId from response - token = response[1]; // Get token from response - console.warn('Request of SESSIONID and TOKEN gone WELL (SESSIONID:' + sessionId + ", TOKEN:" + token + ")"); - callback(); // Continue the join operation - }); + httpRequest( + 'POST', + 'api-sessions/get-token', + {sessionName: sessionName}, + 'Request of TOKEN gone WRONG:', + (response) => { + token = response[0]; // Get token from response + console.warn('Request of TOKEN gone WELL (TOKEN:' + token + ')'); + callback(token); // Continue the join operation + } + ); } function removeUser() { - // Body of POST request with the name of the session and the token of the leaving user - var jsonBody = JSON.stringify({ - 'sessionName': sessionName, - 'token': token - }); - - // Send POST request - httpRequest('POST', 'api-sessions/remove-user', jsonBody, 'User couldn\'t be removed from session', function successCallback(response) { - console.warn(userName + " correctly removed from session"); - }); + httpRequest( + 'POST', + 'api-sessions/remove-user', + {sessionName: sessionName, token: token}, + 'User couldn\'t be removed from session', + (response) => { + console.warn("You have been removed from session " + sessionName); + } + ); } function httpRequest(method, url, body, errorMsg, callback) { @@ -185,7 +193,7 @@ function httpRequest(method, url, body, errorMsg, callback) { http.open(method, url, true); http.setRequestHeader('Content-type', 'application/json'); http.addEventListener('readystatechange', processRequest, false); - http.send(body); + http.send(JSON.stringify(body)); function processRequest() { if (http.readyState == 4) { @@ -209,7 +217,7 @@ function httpRequest(method, url, body, errorMsg, callback) { /* APPLICATION BROWSER METHODS */ -window.onbeforeunload = function () { // Gracefully leave session +window.onbeforeunload = () => { // Gracefully leave session if (session) { removeUser(); leaveSession(); @@ -279,7 +287,7 @@ function initMainVideoThumbnail() { $('#main-video video').css("background", "url('images/subscriber-msg.jpg') round"); } -function isPublisher() { +function isPublisher(userName) { return userName.includes('publisher'); } diff --git a/openvidu-js-java/src/main/resources/static/index.html b/openvidu-js-java/src/main/resources/static/index.html index 9ba4bc00..e480d351 100644 --- a/openvidu-js-java/src/main/resources/static/index.html +++ b/openvidu-js-java/src/main/resources/static/index.html @@ -7,17 +7,14 @@ - - - + + + - +