Пример #1
1
function tokbox()
{
    $current_user = wp_get_current_user();
    $skillid = $_POST['skillid'];
    $myoptions = get_option('tokbox_settings');
    $apiKey = $myoptions['tokbox_account_api_key'];
    $apiSecret = $myoptions['tokbox_secret'];
    //get advisor id
    $skill = get_post($skillid);
    $advisor_id = $skill->post_author;
    $advisor_session_id = get_user_meta($advisor_id, 'webrtcSessionID', true);
    $opentok = new OpenTok($apiKey, $apiSecret);
    // Set some options in a token
    $token = $opentok->generateToken($advisor_session_id, array('role' => 'publisher', 'expireTime' => time() + 7 * 24 * 60 * 60, 'data' => (string) $current_user->ID));
    $return = array('apiKey' => $apiKey, 'sessionId' => $advisor_session_id, 'token' => $token);
    wp_send_json_success($return);
}
Пример #2
1
function WebRTC_advisor_generate_token()
{
    $current_user = wp_get_current_user();
    $myoptions = get_option('tokbox_settings');
    $apiKey = $myoptions['tokbox_account_api_key'];
    $apiSecret = $myoptions['tokbox_secret'];
    $advisor_sessionID = get_user_meta($current_user->ID, 'webrtcSessionID', true);
    //echo $advisor_sessionID;die;
    $opentok = new OpenTok($apiKey, $apiSecret);
    $token = $opentok->generateToken($advisor_sessionID, array('role' => 'publisher', 'expireTime' => time() + 7 * 24 * 60 * 60, 'data' => (string) $current_user->ID));
    //echo 'token - '.$token;
    $return = array('token' => $token, 'apiKey' => $apiKey, 'sessionId' => $advisor_sessionID);
    wp_send_json_success($return);
}
Пример #3
1
 public function testGeneratesTokenWithData()
 {
     // Arrange
     // This sessionId is a fixture designed by using a known but bogus apiKey and apiSecret
     $sessionId = '1_MX4xMjM0NTY3OH4-VGh1IEZlYiAyNyAwNDozODozMSBQU1QgMjAxNH4wLjI0NDgyMjI';
     $bogusApiKey = '12345678';
     $bogusApiSecret = '0123456789abcdef0123456789abcdef0123456789';
     $opentok = new OpenTok($bogusApiKey, $bogusApiSecret);
     // Act
     $userStatus = '{nick:"johnny",status:"hey there fellas!"}';
     $token = $opentok->generateToken($sessionId, array('data' => $userStatus));
     // Assert
     $this->assertInternalType('string', $token);
     $decodedToken = TestHelpers::decodeToken($token);
     $this->assertEquals($sessionId, $decodedToken['session_id']);
     $this->assertEquals($bogusApiKey, $decodedToken['partner_id']);
     $this->assertNotEmpty($decodedToken['nonce']);
     $this->assertNotEmpty($decodedToken['create_time']);
     $this->assertEquals($userStatus, $decodedToken['connection_data']);
     $this->assertNotEmpty($decodedToken['role']);
     // TODO: should all tokens have a default expire time even if it wasn't specified?
     //$this->assertNotEmpty($decodedToken['expire_time']);
     $this->assertNotEmpty($decodedToken['sig']);
     $this->assertEquals(hash_hmac('sha1', $decodedToken['dataString'], $bogusApiSecret), $decodedToken['sig']);
 }
Пример #4
0
//    the user to all other users who connect to it.
//
// NOTE: This request allows anonymous access, but if user authentication is required then the
// identity of the request should be verified (often times with session cookies) before a valid
// response is given.
// NOTE: Uniqueness of names is not enforced.
$app->post('/users', function () use($app, $opentok, $config) {
    $rawBody = $app->request->getBody();
    $params = json_decode($rawBody);
    // Parameter validation
    $name = $params->name;
    if (empty($name) || strlen($name) > intval(NAME_MAX_LENGTH)) {
        $app->response->setStatus(400);
        return;
    }
    $token = $opentok->generateToken($config->opentok('presenceSession'), array('data' => json_encode(array('name' => $name)), 'role' => Role::SUBSCRIBER));
    $responseData = array('token' => $token);
    $app->response->headers->set('Content-Type', 'application/json');
    $app->response->setBody(json_encode($responseData));
});
// Create a chat
//
// Request: (JSON encoded)
// *  `invitee`: the name of the other user who is being invited to the chat
//
// Response: (JSON encoded)
// *  `apiKey`: an OpenTok API key that owns the session ID
// *  `sessionId`: an OpenTok session ID to conduct the chat within
// *  `token`: a token that the creator of the chat (or inviter) can use to connect to the chat
//    session
//
Пример #5
0
    $appointmentInfo = mysqli_fetch_assoc($result);
    // delete record
    sendQuery("DELETE FROM Schedules WHERE Timestamp='{$timestamp}'");
    sendEmail('TokBox Demo', '*****@*****.**', $appointmentInfo['Name'], $appointmentInfo['Email'], "Cancelled: Your TokBox appointment on " . $appointmentInfo['Timestring'], "Your appointment on " . $appointmentInfo['Timestring'] . ". has been cancelled. We are sorry for the inconvenience, please reschedule on " . getBaseURL() . "/index.php/");
    header("Content-Type: application/json");
    echo json_encode($appointmentInfo);
});
$app->post('/schedule', function () use($app, $con, $opentok) {
    $name = $app->request->post("name");
    $email = $app->request->post("email");
    $comment = $app->request->post("comment");
    $timestamp = $app->request->post("timestamp");
    $daystring = $app->request->post("daystring");
    $session = $opentok->createSession();
    $sessionId = $session->getSessionId();
    $timestring = $app->request->post("timestring");
    $query = sprintf("INSERT INTO Schedules (Name, Email, Comment, Timestamp, Daystring, Sessionid, Timestring) VALUES ('%s', '%s', '%s', '%d', '%s', '%s', '%s')", mysqli_real_escape_string($con, $name), mysqli_real_escape_string($con, $email), mysqli_real_escape_string($con, $comment), intval($timestamp), mysqli_real_escape_string($con, $daystring), mysqli_real_escape_string($con, $sessionId), mysqli_real_escape_string($con, $timestring));
    sendQuery($query);
    sendEmail('TokBox Demo', '*****@*****.**', $name, $email, "Your TokBox appointment on " . $timestring, "You are confirmed for your appointment on " . $timestring . ". On the day of your appointment, go here: " . getBaseURL() . "/index.php/chat/" . $sessionId);
    $app->render('schedule.php');
});
$app->get('/rep', function () use($app) {
    $app->render('rep.php');
});
$app->get('/chat/:session_id', function ($session_id) use($app, $con, $apiKey, $opentok) {
    $result = sendQuery("SELECT * FROM Schedules WHERE Sessionid='{$session_id}'");
    $appointmentInfo = mysqli_fetch_assoc($result);
    $token = $opentok->generateToken($session_id);
    $app->render('chat.php', array('name' => $appointmentInfo['Name'], 'email' => $appointmentInfo['Email'], 'comment' => $appointmentInfo['Comment'], 'apiKey' => $apiKey, 'session_id' => $session_id, 'token' => $token));
});
$app->run();
Пример #6
0
        $apiObj = new OpenTok($apiKey, $apiSecret);
    } catch (Exception $e) {
        echo "<div style='background:white;padding:15px;'>Please ask your administrator to configure this plugin using administration panel.</div>";
        exit;
    }
}
if ($_REQUEST['action'] == 'request') {
    if ($videoPluginType == '2') {
        $location = time();
        if (!empty($_SERVER['REMOTE_ADDR'])) {
            $location = $_SERVER['REMOTE_ADDR'];
        }
        try {
            $session = $apiObj->createSession(array('location' => $location));
            $grp = $session->getSessionId();
            $avchat_token = $apiObj->generateToken($grp);
        } catch (Exception $e) {
            echo "<div style='background:white;padding:15px;'>Please ask your administrator to configure this plugin using administration panel.</div>";
            exit;
        }
    } else {
        $grp = time();
    }
    sendMessage($_REQUEST['to'], $broadcast_language[2] . " <a href='javascript:void(0);' onclick=\"javascript:jqcc.ccbroadcast.accept('" . $userid . "','" . $grp . "');\">" . $broadcast_language[3] . "</a> " . $broadcast_language[4], 1);
    sendMessage($_REQUEST['to'], $broadcast_language[5], 2);
    if (!empty($_REQUEST['callback'])) {
        header('content-type: application/json; charset=utf-8');
        echo $_REQUEST['callback'] . '()';
    }
}
if ($_REQUEST['action'] == 'call') {
Пример #7
0
<body style="background-image: url('video_page/img/sky.jpg'); background-size: cover">

    <div id="videos">
        <div id="subscriber"></div>
        <div id="publisher"></div>
    </div>

	<div style="height: 5%"></div>

	<?php 
require "video_page/opentok.phar";
use OpenTok\OpenTok;
//$sessionID = $_POST["sessionID"];
$sessionID = "1_MX40NTQyNzc3Mn5-MTQ0OTM3NDM1MTk4Mn5MVStKL1lkVVBQcHN1L0pDWDMydmxMMjl-UH4";
$opentok = new OpenTok(45427772, "51ce05e8512d7bb676c94be7fe86cd692b32793a");
$token = $opentok->generateToken($sessionID);
$apiKey = 45427772;
$_POST["userType"] = "asker";
?>

	<script type="text/javascript">
		var apiKey,
			sessionId,
			token,
			session;

		$(document).ready(function() {
			$.get(SAMPLE_SERVER_BASE_URL + '/session', function(res) {
				apiKey = <?php 
echo $apiKey;
?>
Пример #8
0
    // Dequeue the next help session
    $redisResponse = $redis->lpop(HELP_QUEUE_KEY);
    if (!handleRedisError($redisResponse, $app, 'Não foi possível atender a uma sessão de vídeo chat da fila.')) {
        return;
    }
    $helpSessionKey = $redisResponse;
    if (empty($helpSessionKey)) {
        // The queue was empty
        $app->response->setStatus(204);
    } else {
        $redisResponse = $redis->hgetall($helpSessionKey);
        if (!handleRedisError($redisResponse, $app, 'Não foi possível ler a sessão de vídeo chat.')) {
            return;
        }
        $helpSessionData = $redisResponse;
        $responseData = array('apiKey' => $config->opentok('key'), 'sessionId' => $helpSessionData['sessionId'], 'token' => $opentok->generateToken($helpSessionData['sessionId']), 'customerName' => $helpSessionData['customerName'], 'problemText' => $helpSessionData['problemText']);
        // Once the help session is dequeued, we also clean it out of the storage.
        // If keeping the history of this help session is important, we could mark it as dequeued
        // instead. If we had authentication for the representative, then we could also mark the
        // help session with the identity of the representative.
        $redisResponse = $redis->del($helpSessionKey);
        if (!handleRedisError($redisResponse, $app, 'Não foi possível remover a sessão após a retirada da fila.')) {
            return;
        }
        $app->response->headers->set('Content-Type', 'application/json');
        $app->response->setBody(json_encode($responseData));
    }
});
// Customer dequeues by cancelling or leaving the page
//
// Dequeue the specific help session from the help queue.
Пример #9
0
        // escape variables for security
        $roomname = mysqli_real_escape_string($con, $roomname);
        $sessionId = mysqli_real_escape_string($con, $sessionId);
        $currentTime = $date->getTimestamp();
        $sql = "INSERT INTO Rooms (Name, Sessionid, User1) VALUES ('{$roomname}', '{$sessionId}', '{$currentTime}')";
        if (!mysqli_query($con, $sql)) {
            die('Error: ' . mysqli_error($con));
        }
        $row = array();
        $row['Name'] = $roomname;
        $row['Sessionid'] = $sessionId;
        $roomAvailable = true;
    } else {
        if (intval($date->getTimestamp()) - intval($row['User1']) > 60) {
            // user1 has not been in the room for > 180 seconds
            $roomAvailable = true;
        } elseif (intval($date->getTimestamp()) - intval($row['User2']) > 60) {
            $userPos = 'User2';
            $roomAvailable = true;
        }
    }
    if ($roomAvailable) {
        $row['apiKey'] = $apiKey;
        $row['roomname'] = $roomname;
        $row['token'] = $opentok->generateToken($row['Sessionid'], array('data' => $userPos));
        $app->render('chat.php', $row);
    } else {
        echo "Room is full at the moment. Please try again in a few minutes";
    }
});
$app->run();
Пример #10
0
// response is given.
$app->delete('/help/queue', function () use($app, $con, $opentok, $config) {
    // Dequeue the next help session
    $query = "SELECT SessionId FROM Sessions WHERE QueueEntryTime IS NOT NULL AND SessionEndTime IS NULL ORDER BY QueueEntryTime LIMIT 1;";
    $result = sendQuery($query);
    // Handle errors
    if (!handleMySqlError($result, $app, 'Could not dequeue a user.')) {
        return;
    }
    $sessionInfo = mysqli_fetch_assoc($result);
    if (!$sessionInfo['SessionId']) {
        // The queue was empty
        $app->response->setStatus(204);
    } else {
        $representativeName = $app->request->params('representativeName');
        $responseData = array('apiKey' => $config->opentok('key'), 'sessionId' => $sessionInfo['SessionId'], 'token' => $opentok->generateToken($sessionInfo['SessionId']));
        // Update the entry on database to set Conversation Start Time and Representative Name
        $query = sprintf("UPDATE Sessions SET ConversationStartTime = NOW(), RepresentativeName = '%s' WHERE SessionId = '%s'", mysqli_real_escape_string($con, $representativeName), mysqli_real_escape_string($con, $sessionInfo['SessionId']));
        $result = sendQuery($query);
        $app->response->headers->set('Content-Type', 'application/json');
        $app->response->setBody(json_encode($responseData));
    }
});
// Updates the Sessions Table when the session is ended either by the customer or by the representative.
$app->delete('/help/queue/:sessionId', function ($sessionId) use($app, $con) {
    // Dequeue the next help session
    $query = sprintf("UPDATE Sessions SET SessionEndTime = NOW() WHERE SessionId = '%s';", mysqli_real_escape_string($con, $sessionId));
    $result = sendQuery($query);
    // Handle errors
    if (!handleMySqlError($result, $app, 'Could not end the session.')) {
        return;
Пример #11
0
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "http://api.opentok.com/session/create");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-TB-PARTNER-AUTH: {$key}:{$secret}"));
curl_setopt($ch, CURLOPT_POST, 1);
$output = curl_exec($ch);
// close curl resource to free up system resources
curl_close($ch);
// parse response
$p = xml_parser_create();
xml_parse_into_struct($p, $output, $vals, $index);
xml_parser_free($p);
$creds = array();
foreach ($vals as $entry) {
    if ($entry["tag"] == "SESSION_ID") {
        $creds['sessionId'] = $entry['value'];
    }
}
// return empty on failure
if (!isset($creds['sessionId'])) {
    $creds['sessionId'] = 0;
    $creds['token'] = 0;
} else {
    // create token
    $openTok = new OpenTok($key, $secret);
    $creds['token'] = $openTok->generateToken($creds['sessionId']);
}
echo json_encode($creds);
?>