DELETE '/api-sessions/:sessionId/connection/:connectionId' request

Hello,

How can I manage the sessions lifecycle to do this request succesfully after my POST /api-sessions/get-token and my POST /api-sessions/remove-user? Any schema about that?

Many thanks,
Beka

Those are not REST API methods of OpenVidu Server. Also, what are you referring to with “managing the sessions lifecycle to do that request”? You can perform any REST API method whenever you want.

No, I am calling them in this case from openvidu-node-client wrapper following the tutorial openvidu-js-node in the back-end part and connecting with angular as front-end. This works fine in fact requesting the REST API /api/sessions and the REST APi /api/tokens from Openvidu Server. My problem is when I need to request /api-sessions/:sessionId or anything which needs session.fetch.This topic is related Problem in GET /api-sessions/:sessionId. There I include code and logs.

I am thinking that maybe I am doing something wrong relating to session lifeycle or something like that, but if you said that " I can perform any REST API method whenever I want"… I don’t know what happens exactly.

Ok, so this is all contextualized in openvidu-js-node tutorial.

But reading the post you linked and this very same message I do not still have a clear idea of your problem. What do you exaclty expect to happen and what behavior are you getting instead?

Can you describe the problem you have when using openvidu-node-client? If you want you can share you application’s code and give us instructions to replicate the issue. If we are able to replicate the problem we will solve it. And if it is a missunderstanding of OpenVidu sessions lifecycle we can tell you what might be wrong.

Cheers!

Ok. I will try to explain better. The final features that I want to build are:

  • A request from angular to OV Server Rest API using openvidu-node-client to close a session for the moderator (leave session for all the participants is working already).
    -A request to ban an user from angular to OV Server Rest API using openvidu-node-client. I have already built a user list in the room and a button to ban any of the participants(only visible for moderator). When the moderator press it an angular service build a request like DELETE ‘/api-sessions/:sessionId/connection/:connectionId’. I need to prepare the controller in openvidu-node-client.
    -A request to unpublish an user from angular to OV server using openvidu-node-client. I have a button equivalent to the previous one. When the moderator press it, an angular service build a request like DELETE ‘’/api-sessions/:sessionId/stream/:streamId’. I need to prepare the controller in openvidu-node-client.

These are the final goals. I am right now doing some previous tests to figure out how to build that controllers in openvidu-node-client. I don’t understand well session.fetch method, I think. I need to understand this well to be able to build that controllers.

// Environment variable: URL where our OpenVidu server is listening
var OPENVIDU_URL = process.argv[2];
// Environment variable: secret shared with our OpenVidu server
var OPENVIDU_SECRET = process.argv[3];

// Entrypoint to OpenVidu Node Client SDK
var OV = new OpenVidu(OPENVIDU_URL, OPENVIDU_SECRET);

// Collection to pair session names with OpenVidu Session objects
var mapSessions = {};
// Collection to pair session names with tokens
var mapSessionIdTokens = {};

var activeConnections = {};

console.log("App listening on port 5000");

/* CONFIGURATION OV/Firebase/Node*/

/* REST API */


// Get token (add new user to session)
app.post('/api-sessions/get-token', function (req, res) {

        // The video-call to connect
        var sessionId = req.body.customSessionId;
        console.log(sessionId);

        var serverData = req.body.serverData;
        console.log(serverData);

        var role = req.body.role;

        console.log(role);

        // Build TokenOptions object with the serverData and the role
        var tokenOptions = {
        role: role
        }

        if (mapSessions[sessionId]) {
            console.log(sessionId);
            // Session already exists
            console.log('Existing session ' + sessionId);


            // Get the existing Session from the collection
            var mySession = mapSessions[sessionId];
            console.log(mySession);
            // Generate a new token asynchronously with the recently created TokenOptions
            mySession.generateToken(tokenOptions)
                .then(token => {

                    // Store the new token in the collection of tokens
                    mapSessionIdTokens[sessionId].push(token);

                    console.log(token);

                    // Return the token to the client
                    res.status(200).send({
                        0: token
                    });
                })
                .catch(error => {
                    console.error(error);
                });
        } else {
            // New session
            console.log('New session ' + sessionId);

            // Create a new OpenVidu Session asynchronously
            OV.createSession()
                .then(session => {
                    // Store the new Session in the collection of Sessions
                    mapSessions[sessionId] = session;
                    // Store a new empty array in the collection of tokens
                    mapSessionIdTokens[sessionId] = [];

                    // Generate a new token asynchronously with the recently created TokenOptions
                    session.generateToken(tokenOptions)
                        .then(token => {

                            // Store the new token in the collection of tokens
                            mapSessionIdTokens[sessionId].push(token);

                            console.log(token);
                            
                            // Return the Token to the client
                            res.status(200).send({
                                0: token
                            });

                            session.fetch().then(anyChange => {
                              activeConnections[sessionId] = session.activeConnections;
                              console.log(activeConnections);
                            });
                        })
                        .catch(error => {
                            console.error(error);
                        });
                })
                .catch(error => {
                    console.error(error);
                });
        }
    });

// Remove user from session
app.post('/api-sessions/remove-user', function (req, res) {
        // Retrieve params from POST body
        var sessionId = req.body.sessionId;
        var token = req.body.token;
        console.log('Removing user | {sessionName, token}={' + sessionId + ', ' + token + '}');

        // If the session exists
        if (mapSessions[sessionId] && mapSessionIdTokens[sessionId]) {
            var tokens = mapSessionIdTokens[sessionId];
            console.log(tokens);
            var index = tokens.indexOf(token);

            // If the token exists
            if (index !== -1) {
                // Token removed
                tokens.splice(index, 1);
                console.log(sessionId + ': ' + tokens.toString());
            } else {
                var msg = 'Problems in the app server: the TOKEN wasn\'t valid';
                console.log(msg);
                res.status(500).send(msg);
            }
            if (tokens.length == 0) {
                // Last user left: session must be removed
                console.log(sessionId + ' empty!');
                delete mapSessions[sessionId];
            }
            res.status(200).send();
        } else {
            var msg = 'Problems in the app server: the SESSION does not exist';
            console.log(msg);
            res.status(500).send(msg);
        }
    });

app.get('/api-sessions/', function (req, res) {
        // Fetch all session info from OpenVidu Server
        OV.fetch()
            .then(anyChange => {
                var activeSessions = OV.activeSessions;
                console.log(activeSessions);
                res.status(200).send();
            });

    });
app.get('/api-sessions/:sessionId', function (req, res){
     session.fetch()
            .then(anyChange =>{
      // Fetch one session info from OpenVidu Server
       var activeConnections = session.activeConnections;
       console.log(activeConnections);
       res.status(200).send();
            });

I have this output in my console:

geeksha@debian:~/vcnton/server$ node server.js https://localhost:4443 MY_SECRET
App listening on port 5000
Mongoose connected to mongodb://localhost:27017/vcnton
zoom
{ username: ‘madrona’ }
MODERATOR
New session zoom
wss://localhost:4443?sessionId=wgcuorfu0e84ox9g&token=ka9dbjxoaexuz71z&role=MODERATOR&version=2.11.0
Session info fetched for session ‘wgcuorfu0e84ox9g’. Any change: true
{ zoom:
[ Connection {
publishers: ,
subscribers: ,
connectionId: ‘uzl7ydoa7hkydggi’,
createdAt: 1579631654479,
role: ‘MODERATOR’,
token:
‘wss://localhost:4443?sessionId=wgcuorfu0e84ox9g&token=ka9dbjxoaexuz71z&role=MODERATOR&version=2.11.0’,
location: ‘unknown’,
platform: ‘Chrome 78.0.3904.108 on Linux 64-bit’,
serverData: ‘’,
clientData: ‘{“clientData”:“madrona”,“role”:“MODERATOR”}’ } ] }
zoom
{ username: ‘geekshabeka’ }
PUBLISHER
zoom
Existing session zoom
Session {
ov:
OpenVidu {
urlOpenViduServer: ‘https://localhost:4443’,
Buffer:
{ [Function: Buffer]
TYPED_ARRAY_SUPPORT: true,
poolSize: 8192,
from: [Function],
alloc: [Function],
allocUnsafe: [Function],
allocUnsafeSlow: [Function],
isBuffer: [Function: isBuffer],
compare: [Function: compare],
isEncoding: [Function: isEncoding],
concat: [Function: concat],
byteLength: [Function: byteLength] },
activeSessions: [ [Circular] ],
hostname: ‘localhost’,
port: 4443,
basicAuth: ‘Basic T1BFTlZJRFVBUFA6TVlfU0VDUkVU’ },
activeConnections:
[ Connection {
publishers: ,
subscribers: ,
connectionId: ‘uzl7ydoa7hkydggi’,
createdAt: 1579631654479,
role: ‘MODERATOR’,
token:
‘wss://localhost:4443?sessionId=wgcuorfu0e84ox9g&token=ka9dbjxoaexuz71z&role=MODERATOR&version=2.11.0’,
location: ‘unknown’,
platform: ‘Chrome 78.0.3904.108 on Linux 64-bit’,
serverData: ‘’,
clientData: ‘{“clientData”:“madrona”,“role”:“MODERATOR”}’ } ],
recording: false,
properties:
{ mediaMode: ‘ROUTED’,
recordingMode: ‘MANUAL’,
defaultOutputMode: ‘COMPOSED’,
defaultRecordingLayout: ‘BEST_FIT’ },
sessionId: ‘wgcuorfu0e84ox9g’,
createdAt: 1579631654336 }
wss://localhost:4443?sessionId=wgcuorfu0e84ox9g&token=wajvvx6xkjhaurqo&role=PUBLISHER&version=2.11.0

So, I created a session and join two users there. I have session.fetch but my console is only giving the information about the first connectionId and not about the second one. I want to get all the active connections.

With Postman and the same openvidu-node-client code which I pasted it, I tried to request GET /api-sessions and the console gives the expected information about active sessions.

With Postman and the same openvidu-node-client which I pasted it, I tried to request /api-sessions/:sessionId and the console gives me session.fetch is not a function.

Really, really thanks for the help. I hope that these snippets are more understable :slight_smile:

Sorry, I was editing this post. It was with a mistake.

Okey, so you want to get the information of the activeConnections of your session “zoom”. You want to get 1 active connection after first user joins the session and you want to get 2 active connections after second user joins the session.

First of all: an active connection is only generated when users actually join the session. Generating tokens is not joining users to a session. Users join a session when they have successfully called Session.join(token) on the client-side code.

Session.fetch in openvidu-node-client will bring the current status of a session from OpenVidu Server by consuming the same REST API you said works fine when using POSTMAN. You just have to call Session.fetch in the right place to get your 2 active connections. If you want to actively listen for new users connecting to the session in your node backend, you can use OpenVidu WebHook or you can add other custom http endpoints to your application’s backend that can be called by your clients when successfully connecting to a session (or when performing any other action, that’s up to you).

By the way, if you find it easier, the 2 last features of the 3 you listed can be implemented directly with openvidu-browser, without consuming OpenVidu Server REST API as you intended. I’m refering to your calls DELETE ‘/api-sessions/:sessionId/connection/:connectionId’ and DELETE ‘’/api-sessions/:sessionId/stream/:streamId’. Moderators can directly call forceDisconnect and forceUnpublish over any other participant of a session. That way you can save http endpoints and network traffic by directly communicating client-openviduserver.

1 Like

I am coming back to these features. Until now, I start to listen through the OV webhook. It’s amazing as the CDR log option.

Hello,

I did the three ones in secure way (avoiding doing the request from the front to protect my ovserver password) but calling OV server REST API directly with axios from node without using openvidu-node-client (I use it for another requests like the ones to create the session for example). It was the way more confortable for me.

Updating the conclusion :slight_smile: