Skip to content

Instantly share code, notes, and snippets.

@doomhz
Created August 20, 2012 10:12
Show Gist options
  • Save doomhz/3402843 to your computer and use it in GitHub Desktop.
Save doomhz/3402843 to your computer and use it in GitHub Desktop.
OpenTok multiple sessions final implementation
<!DOCTYPE HTML>
<html lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<title>OpenTok API Sample &#8212; Basic Tutorial</title>
<link href="samples.css" type="text/css" rel="stylesheet" >
<script src="http://staging.tokbox.com/v0.91/js/TB.min.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<script type="text/javascript" charset="utf-8">
var apiKey = ''; // Replace with your API key. See http://www.tokbox.com/
var sessionId = ''; // Replace with your own session ID. See http://www.tokbox.com/opentok/api/tools/generator
var token = ''; // Replace with a generated token. See http://www.tokbox.com/opentok/api/tools/generator
var session;
var publisher;
var subscribers = {};
function setupSessionData() {
sessionId = document.getElementById("session-id").value;
token = document.getElementById("session-token").value;
apiKey = document.getElementById("api-key").value || apiKey;
}
// Un-comment either of the following to set automatic logging and exception handling.
// See the exceptionHandler() method below.
TB.setLogLevel(TB.DEBUG);
TB.addEventListener("exception", exceptionHandler);
function initSession() {
if (TB.checkSystemRequirements() != TB.HAS_REQUIREMENTS) {
alert("You don't have the minimum requirements to run this application."
+ "Please upgrade to the latest version of Flash.");
} else {
setupSessionData();
session = TB.initSession(sessionId); // Initialize session
// Add event listeners to the session
session.addEventListener('sessionConnected', sessionConnectedHandler);
session.addEventListener('sessionDisconnected', sessionDisconnectedHandler);
session.addEventListener('connectionCreated', connectionCreatedHandler);
session.addEventListener('connectionDestroyed', connectionDestroyedHandler);
session.addEventListener('streamCreated', streamCreatedHandler);
session.addEventListener('streamDestroyed', streamDestroyedHandler);
}
}
function destroySession() {
session.removeEventListener('sessionConnected', sessionConnectedHandler);
session.removeEventListener('sessionDisconnected', sessionDisconnectedHandler);
session.removeEventListener('connectionCreated', connectionCreatedHandler);
session.removeEventListener('connectionDestroyed', connectionDestroyedHandler);
session.removeEventListener('streamCreated', streamCreatedHandler);
session.removeEventListener('streamDestroyed', streamDestroyedHandler);
session = null;
}
//--------------------------------------
// LINK CLICK HANDLERS
//--------------------------------------
/*
If testing the app from the desktop, be sure to check the Flash Player Global Security setting
to allow the page from communicating with SWF content loaded from the web. For more information,
see http://www.tokbox.com/opentok/build/tutorials/helloworld.html#localTest
*/
function connect() {
initSession();
session.connect(apiKey, token);
}
function disconnect() {
session.disconnect();
//stopPublishing();
}
function reconnect() {
disconnect();
setTimeout(function () {
destroySession();
}, 3000);
setTimeout(function () {
connect();
}, 5000);
}
// Called when user wants to start publishing to the session
function startPublishing() {
if (!publisher) {
var parentDiv = document.getElementById("myCamera");
var publisherDiv = document.createElement('div'); // Create a div for the publisher to replace
publisherDiv.setAttribute('id', 'opentok_publisher');
parentDiv.appendChild(publisherDiv);
publisher = TB.initPublisher(apiKey, publisherDiv.id); // Pass the replacement div id
session.publish(publisher);
} else {
session.publish(publisher);
}
}
function stopPublishing() {
if (publisher) {
session.unpublish(publisher);
}
//publisher = null;
}
//--------------------------------------
// OPENTOK EVENT HANDLERS
//--------------------------------------
function sessionConnectedHandler(event) {
// Subscribe to all streams currently in the Session
for (var i = 0; i < event.streams.length; i++) {
addStream(event.streams[i]);
}
}
function streamCreatedHandler(event) {
// Subscribe to the newly created streams
for (var i = 0; i < event.streams.length; i++) {
addStream(event.streams[i]);
}
}
function streamDestroyedHandler(event) {
// This signals that a stream was destroyed. Any Subscribers will automatically be removed.
// This default behaviour can be prevented using event.preventDefault()
event.preventDefault();
for (var i = 0; i < event.streams.length; i++) {
if (event.streams[i].connection.connectionId == session.connection.connectionId) {
// Our publisher just stopped streaming
//event.preventDefault(); // Don't remove the Publisher from the DOM.
} else {
removeStream(event.streams[i].streamId);
}
}
}
function sessionDisconnectedHandler(event) {
// This signals that the user was disconnected from the Session. Any subscribers and publishers
// will automatically be removed. This default behaviour can be prevented using event.preventDefault()
//publisher = null;
event.preventDefault();
for (var streamId in subscribers) {
removeStream(streamId);
}
}
function connectionDestroyedHandler(event) {
// This signals that connections were destroyed
}
function connectionCreatedHandler(event) {
// This signals new connections have been created.
}
/*
If you un-comment the call to TB.addEventListener("exception", exceptionHandler) above, OpenTok calls the
exceptionHandler() method when exception events occur. You can modify this method to further process exception events.
If you un-comment the call to TB.setLogLevel(), above, OpenTok automatically displays exception event messages.
*/
function exceptionHandler(event) {
console.log("Exception: " + event.code + "::" + event.message);
}
//--------------------------------------
// HELPER METHODS
//--------------------------------------
function addStream(stream) {
// Check if this is the stream that I am publishing, and if so do not publish.
if (stream.connection.connectionId == session.connection.connectionId) {
return;
}
var subscriberDiv = document.createElement('div'); // Create a div for the subscriber to replace
subscriberDiv.setAttribute('id', stream.streamId); // Give the replacement div the id of the stream as its id.
document.getElementById("subscribers").appendChild(subscriberDiv);
subscribers[stream.streamId] = session.subscribe(stream, subscriberDiv.id);
}
function removeStream(streamId) {
var subscriber = subscribers[streamId];
if (subscriber) {
var container = document.getElementById(subscriber.id).parentNode;
session.unsubscribe(subscriber);
delete subscribers[streamId];
try {
// Clean up the subscriber container
document.getElementById("subscribers").removeChild(container);
} catch (e) {
}
}
}
function show(id) {
document.getElementById(id).style.display = 'block';
}
function hide(id) {
document.getElementById(id).style.display = 'none';
}
function loadSessionString(el) {
console.log(el.value);
document.getElementById("session-id").value = el.value;
}
function loadTokenString(el) {
console.log(el.value);
document.getElementById("session-token").value = el.value;
}
</script>
<div id="links">
<input type="button" value="Connect" id ="connectLink" onClick="javascript:connect()" />
<input type="button" value="Leave" id ="disconnectLink" onClick="javascript:disconnect()" />
<input type="button" value="Start Publishing" id ="publishLink" onClick="javascript:startPublishing()" />
<input type="button" value="Stop Publishing" id ="unpublishLink" onClick="javascript:stopPublishing()" />
<input type="button" value="Reconnect" id ="reconnectLink" onClick="javascript:reconnect()" />
</div>
<div id="myCamera" class="publisherContainer"></div>
<div id="subscribers"></div>
<hr />
<div>
<label>API Key</label>
<textarea id="api-key"></textarea>
<br />
<label>Session ID</label>
<textarea id="session-id"></textarea>
<br />
<label>Token</label>
<textarea id="session-token"></textarea>
</div>
<hr />
<div id="opentok_console"></div>
</body>
</html>
@charset "UTF-8";
/* CSS Document
*
* Copyright 2010, TokBox, Inc.
*
*/
body, html {
font-family:'Lucida Grande', 'Trebuchet MS', sans-serif;
color: #4c4c4c;
text-align:left;
background-color: #f0f9fb;
}
h1 {
margin-bottom:10px
}
object {
float: left;
}
a,a:visited {
color: #0099CC;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
hr {
width: 100%;
clear: both;
margin: 10px 0 10px 0;
}
#opentok_console {
float: right;
width: 100%;
font-family: 'courier', monospace;
font-size: 12px;
}
#links {
float: top;
}
#links a, input {
}
#sessionControls {
float: top;
}
#pubControls input {
display: inline;
}
#publishForm {
font-size: 14px;
font-family: Arial, Helvetica, sans-serif;
}
#deviceManagerControls {
font-size: 14px;
font-family: Arial, Helvetica, sans-serif;
}
#action a {
display:none;
}
#localview {
float: left;
width: 250px;
}
div.controls {
width:220px;
padding:10 0 10 0;
font-size: 14px;
}
.videobar {
float: top;
}
.videobar-left {
float: left;
width: 250px;
}
.smalltype {
font-size: 80%;
padding-bottom: 6px;
}
.description {
font-size: 90%;
padding-top: 6px;
}
#controls {
float: left;
text-align: left;
padding-right: 10px;
}
#publisherControls {
display: none;
}
#push-to-talk {
display: none;
}
#manageDevicesBtn {
display:none;
}
#manageDevicesDiv {
display:none;
position:absolute;
width:200px;
left:280px;
background-color:DDD;
padding:10px;
border:4px;
}
#manageDevicesDiv h1{
font-size:18px;
}
#manageDevicesDiv label{
width:100%;
display: block;
margin-top:-4px;
}
#manageDevicesDiv img{
display: block;
margin:auto;
}
#manageDevicesDiv a{
font-size: small;
display: block;
margin-top:-12px;
}
#manageDevicesDiv input{
margin-top:2px;
}
#gainControl{
width:30px;
margin-top:20px;
}
#manageDevicesDiv .volume{
display:inline-block;
position: relative;
vertical-align:top;
height:20px;
width:0;
height:10px;
background-color:lime;
margin-top:10px;
}
#devicePanelContainer {
position: absolute;
left: 250px;
top: 10px;
display:none;
}
#devicePanelCloseButton {
position: relative;
z-index: 10;
margin-left: 285px;
margin-right: 12px;
padding: 3px;
text-align: center;
font-size: 11px;
background-color: lightgrey;
}
#devicePanelBackground {
background-color: lightgrey;
width: 340px;
height: 230px;
}
#devicePanelInset #devicePanel {
position: relative;
top: -74px;
left: -9px;
}
a.settingsClose:link,
a.settingsClose:visited,
a.settingsClose:hover {
text-decoration: none;
cursor: pointer;
}
table {
clear: both;
}
td {
vertical-align: top;
padding-right: 15px;
}
.publisherContainer {
width: 100%;
clear: both;
overflow: hidden;
margin: 10px;
}
.subscriberContainer {
width: 100%;
clear: both;
overflow: hidden;
margin: 10px;
}
#login {
background-color:#999;
border:thin solid #000;
width:400px;
padding:5px;
}
#login input {
display: inline;
border: thin solid #000;
}
#connectionsContainer {
clear:both;
background-color:#CCC;
width:400px;
}
.swfContainer {
float:left;
width: 320;
margin-left: 5px;
}
#recorderElement {
clear:both;
float:left;
}
#playerElement {
clear:both;
float:left;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment