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
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/
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
I have an app where frontend is developed in angularjs and backend with symfony.
I need to have a route like: http://example.com/api/invoices/file?file=foo
So I have this inside my FileController:
/**
* Matches /invoices/file/{filename} exactly
*
* #Route("/invoices/file/{filename}", name="get_invoice_file")
*/
public function getInvoiceFileAction(string $filename, Request $request)
{
$path = $this->get('kernel')->getRootDir() . '/../web/uploads/invoices/' . $filename;
if (!file_exists($path)) {
return new Response('file not found', 404);
}
$file = file_get_contents($path);
$headers = [
'Content-Type' => 'application/pdf',
'Conteng-Length' => filesize($path)
];
return new Response($file, 200, $headers);
}
Inside my angularjs app I have this to get the response inside my frontend controller:
vm.getInvoices = function() {
vm.loading = true;
apiResolver.resolve('invoices.documents.file#get', { "file": vm.searchFile }).then(function(response) {
vm.loading = false;
var file = new Blob([response], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
vm.file = $sce.trustAsResourceUrl(fileURL);
});
};
Into my html I have this:
<embed ng-src="{{vm.file}}" style="width:200px;height:200px;"></embed>
When I render the page I see a 200response so the file exist but into the html I have an empty space instead of pdf file.
Inside embed tag there is this:
<embed style="width:200px;height:200px;" ng-src="blob:http://localhost:3000/d32d87d1-6582-42e3-85ae-dc174ca5a473" src="blob:http://localhost:3000/d32d87d1-6582-42e3-85ae-dc174ca5a473">
If I copy url inside a browser returns me that can't load file.
Backend and frontend are in different folder and the pdf CAN'T be viewed by a public link infact these pages are protected with jwt system.
How can I show inside my page the pdf?
What I'm doing wrong?
Make sure that JWT Authorization Token is passed in the request . If not , pass it in the Blob object.
If token is passed try replacing embed to object as mentioned below :
<object data="{{vm.file}}" style="width:200px;height:200px;" type="application/pdf"></object>
I am getting list of images from a folder for particular ID. Right now I am getting file names but I also want to get upload path.
How to get both data in one function.
Jquery Code:
listFilesOnServer(project_id);
function listFilesOnServer (project_id) {
var items = [];
uploadURI = uploadURI+'/'+project_id;
console.log(project_id+'--KAL--'+uploadURI);
$.getJSON(uploadURI ,function(data,path) {
console.log(data);
$('div #list-group').html("").html(items.join(""));
});
}
Controller Code:
function listFiles() {
$this->load->helper('file');
$project_id = $this->uri->segment(3);
$builders_id = $this->admin_model->getBuilderID($project_id);
$UPLD_PATH = $this->admin_model->builder_UPLD_PATH($builders_id);
$upload_path = "./application/assets/images/" . $UPLD_PATH;
$files = get_filenames($upload_path);
echo json_encode($files);
}
You should modify your controller action so that it returns an json_encode(array('files'=>$yourFiles, 'filePath'=>$yourFilePath) ); like below :
function listFiles() {
$this->load->helper('file');
$project_id = $this->uri->segment(3);
$builders_id = $this->admin_model->getBuilderID($project_id);
$UPLD_PATH = $this->admin_model->builder_UPLD_PATH($builders_id);
$upload_path = "./application/assets/images/" . $UPLD_PATH;
$files = get_filenames($upload_path);
echo json_encode(array('files'=>$files, 'uploadPath'=>$upload_path) );
exit();
}
Then modify your jquery code to handle the json response and extract the response like below :
listFilesOnServer(project_id);
function listFilesOnServer (project_id) {
var items = [];
uploadURI = uploadURI+'/'+project_id;
console.log(project_id+'--KAL--'+uploadURI);
$.getJSON(uploadURI ,function(data,path) {
//Your upload path
console.info("UPLOAD PATH: "+data.uploadPath);
//Your files
console.log(data.files);
//Your processing logic goes here
$('div #list-group').html("").html(items.join(""));
});
}
I'm using ajax to post a value as given below,
but data I post wont reach the controllers ajaxAaction
view script (which is a tpl file)
<input type="text" id='taska'>
<button id='submitTo'>button</button>
script
$(document).ready(
function(){
//controller via ajax
$("#submitTo").click(function() {
var message = $('#taska').val();
if (message != '') {
//run ajax
//alert ('not empty');
$.post('index/ajax',
{'message' : message},
//callback function
function (respond) {
//put respond in class show-msg
$(".show-msg").html(respond);
}
);
}
});
and the action
public function ajaxAction() {
//get post request (standart approach)
$request = $this->getRequest()->getPost();
//referring to the index
//gets value from ajax request
$message = $request['message'];
// makes disable renderer
$this->_helper->viewRenderer->setNoRender();
//makes disable layout
$this->_helper->getHelper('layout')->disableLayout();
//return callback message to the function javascript
echo $message;
}
} );
$.post('index/ajax', is the part where I think the error is.
Am I defining the controller and action in the wrong way?
I've been stuck here for a while.
please help
try it with $this->basePath() in <?php echo $this->basePath();?>index/ajax
Solved it by prefixing the rootPath as below
if (message != '') {
//run ajax rootPath
{/literal} $.post("{eval var=$rootPath}/index/ajax", {literal}
{'message' : message},
//callback function
function (respond) {
I tried to Use the Telerik component Upload in asp mvc .
#(Html.Telerik().Upload()
.Name("attachement")
.Multiple(true)
.Async(async => async
.Save("Save", "Image")
.Remove("Remove", "Image")
.AutoUpload(true)
).ClientEvents(events => events.OnSuccess("onSuccess")))
In My Controller I have:
public ActionResult Save(HttpPostedFileBase attachement)
{
var fileName = attachement.FileName;
Guid id = SaveImage(attachement);
return Json(
new
{
Succces = true,
Content=id,
}
);
}
In my View I need to display the content of the Json Result ,
I have a event on the uploader called OnSucces
function onSuccess(e) {
}
How Can I get the JsonContent in this method javascript and display the content .
Or all this logic is wrong .
Thanks in advance
Check the sending and receiving metadata help article.