0

I am working on Tokbox video calling process. Now I am using the sample kit of Tokbox which is working properly but it is showing me all active user video.

but I need one user can video calling to another user.

I mean I need one to one video calling process. Is It possible in Tokbox. So please help to solve out it.

This is My code

use Slim\Slim;
use Gregwar\Cache\Cache;
use OpenTok\OpenTok;

if(!empty($userid))
{
$autoloader = __DIR__.'/../../../component/tokbox/vendor/autoload.php'; 
if (!file_exists($autoloader)) {
  die('You must run `composer install` in the sample app directory');
}

require($autoloader);



// PHP CLI webserver compatibility, serving static files
$filename = __DIR__.preg_replace('#(\?.*)$#', '', $_SERVER['REQUEST_URI']);
if (php_sapi_name() === 'cli-server' && is_file($filename)) {
    return false;
}


// Initialize Slim application
$app = new Slim(array(
    'templates.path' => __DIR__
));

// Intialize a cache, store it in the app container
$app->container->singleton('cache', function() {
    return new Cache;
});

// Initialize OpenTok instance, store it in the app contianer
$app->container->singleton('opentok', function () {
    return new OpenTok('***', '****');
});
// Store the API Key in the app container
$app->apiKey = '45833942';
$id=$this->uri->segment('3');
$urlname=$this->uri->segment('4');
// Configure routes
$app->get('/home/livechat/'.$id.'/'.$urlname.'/', function () use ($app) {

    // If a sessionId has already been created, retrieve it from the cache
    $sessionId = $app->cache->getOrCreate('sessionId', array(), function() use ($app) {
        // If the sessionId hasn't been created, create it now and store it
        $session = $app->opentok->createSession();
        return $session->getSessionId();
    });

    // Generate a fresh token for this client
    $token = $app->opentok->generateToken($sessionId);

/*$this->db->select('activemember');
$this->db->from('pshy_videocat');
$psychics=$this->db->get();
$totaluseractive= $psychics->row();
$totalactivevideouser=$totaluseractive->activemember;*/


   ?>

 <input type="hidden" id="connectionCountField" value="0"></input>
 <!--button onclick="myFunction()">Toggle Video</button-->
 <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
 <script src="https://static.opentok.com/v2/js/opentok.js" charset="utf-8"></script>

 <script charset="utf-8">
 var publisher;
 var connectionCount = 0;

 var apiKey = '<?php echo '45833942'; ?>';
 var sessionId = '<?php echo $sessionId; ?>';
 var token = '<?php echo $token; ?>';

 var subscribeoptions = {width: 664, height: 421, insertMode: 'append'}

 var session = OT.initSession(apiKey, sessionId)
 .on('streamCreated', function(event) {
 session.subscribe(event.stream,'myPublisherDiv', subscribeoptions);
 })
 .connect(token, function(error) { 

 var publisherOptions = {
  insertMode: 'append',
  width: 150,
  height: 150,
  publishAudio:true, 
  publishVideo:true,
  name: "You"
};


 publisher = OT.initPublisher('mycam', publisherOptions);
 session.publish(publisher);
 });

 session.on("connectionCreated", function(event) {
   connectionCount++;
   displayConnectionCount();
});

session.on("connectionDestroyed", function(event) {
   connectionCount--;
   displayConnectionCount();
});

function displayConnectionCount() {
    document.getElementById("connectionCountField").value = connectionCount.toString();
    /*var newdata=connectionCount.toString();
      $.ajax({
            url:$('#baseUrl').val()+"home/updateactiveuser",
            type:'post',
            data: {newdata:newdata}
        })*/
}


 var enableVideo=true;

 function myFunction() {
 if(enableVideo)
 {
 publisher.publishVideo(false);
 enableVideo=false;
 } else
 {
 publisher.publishVideo(true);
 enableVideo=true;
 }
 }
 </script>


<?php 
});

$app->run();
}
?>

Thanks

Lucas Huang
  • 3,998
  • 3
  • 20
  • 29
indresh
  • 29
  • 5
  • You might've using single SESSION ID for all the users. That's why you are getting all users connected to that SESSION. You need to create different SESSION ID for different chat rooms. – Suresh May 05 '17 at 06:09
  • Can you please tell me how can I will generate a different session id – indresh May 08 '17 at 11:06
  • Ref this - https://tokbox.com/developer/sdks/php/#creating-sessions – Suresh May 08 '17 at 11:35
  • I have read it, but I did not get how can I generate different session id for different user at a time. Is it possible by user id or name etc. ? – indresh May 08 '17 at 11:39
  • Whenever you'll create a session id, you'll get a totally new session id. So, if you'll create session id 5 times, then you'll get totally 5 different session ids. – Suresh May 08 '17 at 11:42
  • No, I am getting same session id, on same time on different pc – indresh May 08 '17 at 11:45
  • Can u share your SESSION ID generation code with your post? – Suresh May 08 '17 at 11:48
  • sure, " 2_MX40NTgzMzk0Mn5-MTQ5Mzg4OTY4NTY4NX5DZjNVaTRldlZkbFYrTmlHNStmNWYxem5-UH4 " – indresh May 08 '17 at 11:58
  • Share your whole PHP code by using which you are generating your session ids. So that, we can know how you are generating those ids. – Suresh May 08 '17 at 12:00
  • Every time it is giving me same SESSION ID – indresh May 08 '17 at 12:00
  • Too long character, Where I can give me my all code? – indresh May 08 '17 at 12:02
  • can you please send me your email id – indresh May 08 '17 at 12:03
  • I saw your code. Why you've written all your HTML inside ```$app->get('/home/livechat/'.$id.'/'.$urlname.'/', function () use ($app) { HTML CODE })```? I can't also test that one as I don't have those API KEY+SECRET KEY. – Suresh May 09 '17 at 04:29
  • Are these keys your PAID key or TRIAL keys? If those are trail keys then fine else remove those. By the way, I can't help you right now. Give me some time. – Suresh May 09 '17 at 05:09
  • No, these are trial keys, Just tell me how can I generate different SESSION Id for different User, Is there any way to create a Different SESSION ID – indresh May 09 '17 at 05:14
  • There are no special ways to create different session ids. It just creates a unique session id every time when you try to create a session id. Don't know how in your case you are getting same session id every time. – Suresh May 09 '17 at 05:22
  • I am using a sample SDK. I think It will have a Static SESSION ID. I am right or wrong – indresh May 09 '17 at 05:53
  • Shared a sample code with you with the response. Check that out. – Suresh May 09 '17 at 09:57
  • check this out: https://github.com/opentok/accelerator-core-js https://github.com/opentok/learning-opentok-web – Lucas Huang May 09 '17 at 16:47

2 Answers2

1

Here is a sample code. I've not used SLIM for this. But this can be done with Slim also. I've executed the script 5 times & each time I got a unique Session-Id.

Session Id Received -

Session Id Got : 1_MX40NTgzMzk0Mn5-MTQ5NDMyMzQ0NzU0NH5KNk9Gcy9FSktPSlUwdldUbURwazJ0Umd-QX4
Session Id Got : 2_MX40NTgzMzk0Mn5-MTQ5NDMyMzQ3ODMzM35rWWU5NDV1ZjZPMGhLc3pCS3pRSERJY0h-QX4
Session Id Got : 1_MX40NTgzMzk0Mn5-MTQ5NDMyMzQ5NTcwOX5kc0Q3NDBjQSthOWJaMEk1eUllU3dCY0t-QX4
Session Id Got : 2_MX40NTgzMzk0Mn5-MTQ5NDMyMzUwNzExOH5NMEZuZWRyejBZYnZRVk1zSEczNldocmV-QX4
Session Id Got : 1_MX40NTgzMzk0Mn5-MTQ5NDMyMzUxNzE3NH5Yc0hyMUlacmFqK25pVzhXNDI5NTV6eDB-QX4

Vanilla PHP Script -

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');

require 'vendor/autoload.php';
use OpenTok\OpenTok;

$apiKey = '45833942';
$apiSecret = '9727d4ae20e8695a8f787bc58c0b4a9ebf6aae6e';
$opentok = new OpenTok($apiKey, $apiSecret);

use OpenTok\MediaMode;
use OpenTok\ArchiveMode;


// An automatically archived session:
$sessionOptions = array(
    'archiveMode' => ArchiveMode::ALWAYS,
    'mediaMode' => MediaMode::ROUTED
);
$session = $opentok->createSession($sessionOptions);


// Store this sessionId in the database for later use
$sessionId = $session->getSessionId();


echo "Session Id Got : $sessionId";

SLIM Version -

<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');

use \Psr\Http\Message\ServerRequestInterface as Request;
use \Psr\Http\Message\ResponseInterface as Response;
use OpenTok\OpenTok;
use OpenTok\MediaMode;
use OpenTok\ArchiveMode;

require 'vendor/autoload.php';

$app = new \Slim\App;

$container = $app->getContainer();

$container['opentok'] = function ($c) {
    $apiKey = '45833942';
    $apiSecret = '9727d4ae20e8695a8f787bc58c0b4a9ebf6aae6e';

    $opentok = new OpenTok($apiKey, $apiSecret);
    return $opentok;
};


$app->get('/', function (Request $request, Response $response) {
    // An automatically archived session:
    $sessionOptions = array(
        'archiveMode' => ArchiveMode::ALWAYS,
        'mediaMode' => MediaMode::ROUTED
    );
    $session = $this->opentok->createSession($sessionOptions);

    // Store this sessionId in the database for later use
    $sessionId = $session->getSessionId();

    $response->getBody()->write("Session Id Got : $sessionId");
    return $response;
});

$app->run();

Hope, it'll help you.

Ref : https://tokbox.com/developer/sdks/php/

Suresh
  • 5,687
  • 12
  • 51
  • 80
  • I have question that is Now I have make a user as publisher and second user as subscriber. can you please tell me they can connect and do video calling with each other. Is it possible? Actually both are working but subscribe car see publisher video but publish can't able to see subscriber video so can you please guide me how can it is possible – indresh May 10 '17 at 07:41
  • Of course, they can do video chat with each other. In the case where both users need to communicate with each other then, both should be as Publisher & Subscriber. If one is Publisher & another one is Subscriber then Subscriber can able to see the Publisher's face but Publisher can't able to Subscriber's face because Subscriber is not publishing any video stream to the network. – Suresh May 10 '17 at 11:27
  • It is possible to detect that two publisher are on video streaming? Because I want only two user video streaming at a time – indresh May 10 '17 at 12:08
  • I don't think so that there is any default function or method available to do that. But, as your program is in charge to enable the communication between 2 users by generating all needed Token Ids, you can easily keep a track of it by using yours program. – Suresh May 10 '17 at 12:29
  • Yes, Actually when my user or psychic will closed browser or tab then I am not able to detect him I have used you session destroyed or another session destroyed function like session.on("connectionDestroyed", function(event) { event.preventDefault(); displayConnectionstatus(); }); But they are not workin. So Please guide me how can I update my database on connection lost Regards – indresh May 11 '17 at 14:14
  • Please post a new question regarding this with your code which you've written & got error or whatever. – Suresh May 11 '17 at 15:14
0

Looks like you have based your code on the OpenTok Hello World PHP sample. This sample is written to support a single session only, for demonstration purposes. Your issue here is that you are retrieving the same key (sessionId) from cache every time, which is what the sample does.

You are close. The simplest way to extend this sample to multiple sessions is to store your new session IDs in the cache as different keys. You need to change your code to use different key for storing and retrieving session ID. So, you can change the cache retrieval logic from:

<?php
$sessionId = $app->cache->getOrCreate('sessionId', array(), function() use ($app) {
  # ...
}
?>

to something like:

<?php
# Here we add `$id` from the URI segment to create a unique key
# Notice the change in the key name to `'session' . $id'`
$sessionId = $app->cache->getOrCreate('session' . $id, array(), function() use ($app) {
  # ...
}
?>

At the simplest, your code needs to map your application's live chat ID to an OpenTok session internally. Everytime you request for a new livechat ID, it will create a new OpenTok session and store the new OpenTok session ID internally for that livechat ID.

So, you should have two different sessions if you request:

  • /home/livechat/foo/bar
  • /home/livechat/baz/bar

Bonus

A quick tip on creating OpenTok sessions: This is all you need to create a new session using OpenTok PHP SDK:

<?php
use OpenTok\OpenTok;
$apiObj = new OpenTok($API_KEY, $API_SECRET);

# This function creates an OpenTok session and returns a new session ID
function createOTSession() {
  $session = $apiObj->createSession(array('mediaMode' => MediaMode::ROUTED));
  return $session->getSessionId();
}
?>

Everytime you call $apiObj->createSession(), it creates a new session and you can access the session id by calling getSessionId() on the returned object. If you have a function like createOTSession() above, you can call that function from a route that needs to creates new sessions.

See: Creating OpenTok sessions in PHP

kaustavdm
  • 405
  • 4
  • 11
  • I have question that is Now I have make a user as publisher and second user as subscriber. can you please tell me they can connect and do video calling with each other. Is it possible? Actually both are working but subscribe car see publisher video but publish can't able to see subscriber video so can you please guide me how can it is possible – indresh May 10 '17 at 07:41