-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathvideoChatTokBox.js
87 lines (73 loc) · 2.82 KB
/
videoChatTokBox.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
var videoResolution = {width: 200, height: 150};
window.TBStart = function(apiKey, parentDiv){
this.loadJS = function(){
var fileref=document.createElement('script')
fileref.setAttribute("type","text/javascript")
fileref.setAttribute("src", "https://swww.tokbox.com/webrtc/v2.0/js/TB.min.js")
document.getElementsByTagName("head")[0].appendChild(fileref);
};
var self = this;
this.loadJS();
this.apiKey = apiKey;
this.parentDiv = parentDiv;
this.send = function(){
var room = encodeURIComponent( document.URL );
var xhr = new XMLHttpRequest();
var url = "http://apigenerator.herokuapp.com/getSession?room="+room;
var method = "GET";
if ("withCredentials" in xhr) {
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
}
xhr.onload = function(){
var e = JSON.parse(xhr.responseText);
TB.addEventListener( 'exception', self.exceptionHandler );
var did = "publisherElement";
var div = document.createElement('div');
div.setAttribute('id', did);
div.style.display="inline-block";
document.getElementById( self.parentDiv ).appendChild( div );
self.apiKey = e.apiKey;
self.session_id = e.session_id;
self.token = e.token;
self.publisher = TB.initPublisher( "25740492", did, videoResolution );
self.session = TB.initSession( self.session_id );
self.session.addEventListener( 'sessionConnected', self.sessionConnectedHandler );
self.session.addEventListener( 'streamCreated', self.streamCreatedHandler );
self.session.connect( self.apiKey, self.token );
}
xhr.send();
};
this.exceptionHandler = function(e){
alert(e.message);
};
this.sessionConnectedHandler = function(e){
self.session.publish( self.publisher );
console.log("session connected");
self.subscribeToStreams( e.streams );
};
this.streamCreatedHandler = function(e){
self.subscribeToStreams( e.streams );
};
this.subscribeToStreams = function(streams){
for( var i=0; i<streams.length; i++){
if (streams[i].connection.connectionId == self.session.connection.connectionId) {
return;
}
// Create the div to put the subscriber element in to
var div = document.createElement('div');
div.setAttribute('id', 'stream' + streams[i].streamId);
div.style.display="inline-block";
document.getElementById( self.parentDiv ).appendChild( div );
self.session.subscribe( streams[i], div.id, videoResolution );
}
};
}
TBStart.prototype.startVideo = function(){
this.send();
}