connection.js 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402
  1. function DataConnection(id, peer, socket, httpUrl, cb, options) {
  2. if (!(this instanceof DataConnection)) return new DataConnection(options);
  3. EventEmitter.call(this);
  4. options = util.extend({
  5. config: { 'iceServers': [{ 'url': 'stun:stun.l.google.com:19302' }] },
  6. socketOpen: false
  7. }, options);
  8. this.options = options;
  9. this._id = id;
  10. this._peer = peer;
  11. this._originator = (options.sdp === undefined);
  12. this._cb = cb;
  13. this._httpUrl = httpUrl;
  14. //this._peerReady = true;
  15. this.metadata = options.metadata;
  16. this._socketOpen = options.socketOpen;
  17. this._config = options.config;
  18. // Set up socket handlers.
  19. this._socket = socket;
  20. // Firefoxism: connectDataConnection ports.
  21. if (util.browserisms === 'Firefox') {
  22. this._firefoxPortSetup();
  23. }
  24. //
  25. // Set up PeerConnection.
  26. this._startPeerConnection();
  27. // Listen for ICE candidates
  28. //this._queuedIce = [];
  29. this._setupIce();
  30. // Listen for negotiation needed
  31. // ** Chrome only.
  32. if (util.browserisms === 'Webkit') {
  33. this._setupOffer();
  34. }
  35. // Listen or create a data channel
  36. this._setupDataChannel();
  37. var self = this;
  38. if (options.sdp) {
  39. this.handleSDP({ type: 'OFFER', sdp: options.sdp });
  40. if (util.browserisms !== 'Firefox') {
  41. this._makeAnswer();
  42. }
  43. }
  44. if (util.browserisms === 'Firefox') {
  45. this._firefoxAdditional();
  46. }
  47. };
  48. util.inherits(DataConnection, EventEmitter);
  49. DataConnection.prototype._setupOffer = function() {
  50. var self = this;
  51. util.log('Listening for `negotiationneeded`');
  52. this._pc.onnegotiationneeded = function() {
  53. util.log('`negotiationneeded` triggered');
  54. self._makeOffer();
  55. };
  56. }
  57. DataConnection.prototype._setupDataChannel = function() {
  58. var self = this;
  59. if (this._originator) {
  60. util.log('Creating data channel');
  61. this._dc = this._pc.createDataChannel(this._peer, { reliable: false });
  62. this._configureDataChannel();
  63. } else {
  64. util.log('Listening for data channel');
  65. this._pc.ondatachannel = function(evt) {
  66. util.log('Received data channel');
  67. self._dc = evt.channel;
  68. self._configureDataChannel();
  69. };
  70. }
  71. };
  72. /** Starts a PeerConnection and sets up handlers. */
  73. DataConnection.prototype._startPeerConnection = function() {
  74. util.log('Creating RTCPeerConnection: ', this._config);
  75. this._pc = new RTCPeerConnection(this._config, { optional:[ { RtpDataChannels: true } ]});
  76. };
  77. /** Takes care of ice handlers. */
  78. DataConnection.prototype._setupIce = function() {
  79. util.log('Listening for ICE candidates');
  80. var self = this;
  81. this._pc.onicecandidate = function(evt) {
  82. if (evt.candidate) {
  83. util.log('Received ICE candidates');
  84. self._handleBroker('ice', JSON.stringify({
  85. type: 'CANDIDATE',
  86. candidate: evt.candidate,
  87. dst: self._peer,
  88. src: self._id
  89. }));
  90. /*var data = JSON.stringify({
  91. type: 'CANDIDATE',
  92. candidate: evt.candidate,
  93. dst: self._peer,
  94. src: self._id
  95. });
  96. if (self._peerReady) {
  97. self._handleBroker('ice', data);
  98. } else {
  99. self._queuedIce.push(data);
  100. }*/
  101. }
  102. };
  103. };
  104. DataConnection.prototype._handleBroker = function(type, data) {
  105. if (this._socketOpen) {
  106. this._socket.send(data);
  107. } else {
  108. var self = this;
  109. var http = new XMLHttpRequest();
  110. http.open('post', this._httpUrl + '/' + type, true);
  111. http.setRequestHeader('Content-Type', 'application/json');
  112. http.onload = function() {
  113. // If destination peer is not available...
  114. if (http.responseText != 'OK') {
  115. util.log('Destination peer not available. Connection closing...');
  116. self.close();
  117. }/* else {
  118. if (type == 'offer') {
  119. self.processQueuedIce();
  120. }
  121. }*/
  122. }
  123. http.send(data);
  124. }
  125. };
  126. /*
  127. DataConnection.prototype.processQueuedIce = function() {
  128. this._peerReady = true;
  129. console.log('processing ice');
  130. while (this._queuedIce.length > 0) {
  131. var data = this._queuedIce.shift();
  132. this._handleBroker('ice', data);
  133. }
  134. }
  135. */
  136. // Awaiting update in Firefox spec ***
  137. /** Sets up DataChannel handlers.
  138. DataConnection.prototype._setupDataChannel = function() {
  139. var self = this;
  140. if (this._originator) {
  141. if (util.browserisms === 'Webkit') {
  142. // TODO: figure out the right thing to do with this.
  143. this._pc.onstatechange = function() {
  144. util.log('State Change: ', self._pc.readyState);
  145. }
  146. } else {
  147. this._pc.onconnection = function() {
  148. util.log('ORIGINATOR: onconnection triggered');
  149. self._startDataChannel();
  150. };
  151. }
  152. } else {
  153. this._pc.onconnection = function() {
  154. util.log('SINK: onconnection triggered');
  155. };
  156. }
  157. this._pc.onclosedconnection = function() {
  158. // Remove socket handlers perhaps.
  159. self.emit('close', self._peer);
  160. };
  161. };
  162. */
  163. DataConnection.prototype._firefoxPortSetup = function() {
  164. if (!DataConnection.usedPorts) {
  165. DataConnection.usedPorts = [];
  166. }
  167. this.localPort = util.randomPort();
  168. while (DataConnection.usedPorts.indexOf(this.localPort) != -1) {
  169. this.localPort = util.randomPort();
  170. }
  171. this.remotePort = util.randomPort();
  172. while (this.remotePort === this.localPort ||
  173. DataConnection.usedPorts.indexOf(this.localPort) != -1) {
  174. this.remotePort = util.randomPort();
  175. }
  176. DataConnection.usedPorts.push(this.remotePort);
  177. DataConnection.usedPorts.push(this.localPort);
  178. }
  179. DataConnection.prototype._configureDataChannel = function() {
  180. var self = this;
  181. if (util.browserisms === 'Firefox') {
  182. this._dc.binaryType = 'blob';
  183. }
  184. this._dc.onopen = function() {
  185. util.log('Data channel connection success');
  186. self._cb(null, self);
  187. };
  188. this._dc.onmessage = function(e) {
  189. self._handleDataMessage(e);
  190. };
  191. };
  192. /** Decide whether to handle Firefoxisms. */
  193. DataConnection.prototype._firefoxAdditional = function() {
  194. var self = this;
  195. getUserMedia({ audio: true, fake: true }, function(s) {
  196. self._pc.addStream(s);
  197. if (self._originator) {
  198. self._makeOffer();
  199. } else {
  200. self._makeAnswer();
  201. }
  202. }, function(err) { util.log('Could not getUserMedia'); });
  203. }
  204. DataConnection.prototype._makeOffer = function() {
  205. var self = this;
  206. this._pc.createOffer(function(offer) {
  207. util.log('Created offer');
  208. self._pc.setLocalDescription(offer, function() {
  209. util.log('Set localDescription to offer');
  210. //self._peerReady = false;
  211. self._handleBroker('offer', JSON.stringify({
  212. type: 'OFFER',
  213. sdp: offer,
  214. dst: self._peer,
  215. src: self._id,
  216. metadata: self.metadata
  217. }));
  218. }, function(err) {
  219. self._cb('Failed to setLocalDescription');
  220. util.log('Failed to setLocalDescription, ', err);
  221. });
  222. });
  223. };
  224. /** Create an answer for PC. */
  225. DataConnection.prototype._makeAnswer = function() {
  226. var self = this;
  227. this._pc.createAnswer(function(answer) {
  228. util.log('Created answer');
  229. self._pc.setLocalDescription(answer, function() {
  230. util.log('Set localDescription to answer');
  231. self._handleBroker('answer', JSON.stringify({
  232. type: 'ANSWER',
  233. src: self._id,
  234. sdp: answer,
  235. dst: self._peer
  236. }));
  237. }, function(err) {
  238. self._cb('Failed to setLocalDescription');
  239. util.log('Failed to setLocalDescription, ', err)
  240. });
  241. }, function(err) {
  242. self._cb('Failed to create answer');
  243. util.log('Failed to create answer, ', err)
  244. });
  245. };
  246. DataConnection.prototype._cleanup = function() {
  247. if (!!this._pc && this._pc.readyState != 'closed') {
  248. this._pc.close();
  249. this._pc = null;
  250. }
  251. if (!!this._dc && this._dc.readyState != 'closed') {
  252. this._dc.close();
  253. this._dc = null;
  254. }
  255. this.emit('close', this._peer);
  256. };
  257. // Handles a DataChannel message.
  258. DataConnection.prototype._handleDataMessage = function(e) {
  259. var self = this;
  260. if (e.data.constructor === Blob) {
  261. util.blobToArrayBuffer(e.data, function(ab) {
  262. var data = BinaryPack.unpack(ab);
  263. self.emit('data', data);
  264. });
  265. } else if (e.data.constructor === ArrayBuffer) {
  266. var data = BinaryPack.unpack(e.data);
  267. self.emit('data', data);
  268. } else if (e.data.constructor === String) {
  269. var ab = util.binaryStringToArrayBuffer(e.data);
  270. var data = BinaryPack.unpack(ab);
  271. self.emit('data', data);
  272. }
  273. };
  274. /**
  275. * Exposed functionality for users.
  276. */
  277. /** Allows user to close connection. */
  278. DataConnection.prototype.close = function() {
  279. // TODO: how to emit close to the Peer? Also, how to handle Websocket closing
  280. // gracefully?
  281. this._cleanup();
  282. var self = this;
  283. this._handleBroker('leave', JSON.stringify({
  284. type: 'LEAVE',
  285. dst: self._peer,
  286. src: self._id,
  287. }));
  288. };
  289. /** Allows user to send data. */
  290. DataConnection.prototype.send = function(data) {
  291. var self = this;
  292. var blob = BinaryPack.pack(data);
  293. if (util.browserisms === 'Webkit') {
  294. util.blobToBinaryString(blob, function(str){
  295. self._dc.send(str);
  296. });
  297. } else {
  298. this._dc.send(blob);
  299. }
  300. };
  301. /**
  302. * Exposed functions for Peer.
  303. */
  304. DataConnection.prototype.setSocketOpen = function() {
  305. this._socketOpen = true;
  306. };
  307. DataConnection.prototype.handleSDP = function(message) {
  308. var sdp = message.sdp;
  309. if (util.browserisms != 'Firefox') {
  310. sdp = new RTCSessionDescription(sdp);
  311. }
  312. var self = this;
  313. this._pc.setRemoteDescription(sdp, function() {
  314. util.log('Set remoteDescription: ' + message.type);
  315. // Firefoxism
  316. if (message.type === 'ANSWER' && util.browserisms === 'Firefox') {
  317. self._pc.connectDataConnection(self.localPort, self.remotePort);
  318. self._handleBroker('port', JSON.stringify({
  319. type: 'PORT',
  320. dst: self._peer,
  321. src: self._id,
  322. remote: self.localPort,
  323. local: self.remotePort
  324. }));
  325. }
  326. }, function(err) {
  327. this._cb('Failed to setRemoteDescription');
  328. util.log('Failed to setRemoteDescription, ', err);
  329. });
  330. };
  331. DataConnection.prototype.handleCandidate = function(message) {
  332. var candidate = new RTCIceCandidate(message.candidate);
  333. this._pc.addIceCandidate(candidate);
  334. util.log('Added ice candidate');
  335. };
  336. DataConnection.prototype.handleLeave = function() {
  337. util.log('Peer ' + this._peer + ' disconnected');
  338. this._cleanup();
  339. };
  340. DataConnection.prototype.handlePort = function(message) {
  341. if (!DataConnection.usedPorts) {
  342. DataConnection.usedPorts = [];
  343. }
  344. DataConnection.usedPorts.push(message.local);
  345. DataConnection.usedPorts.push(message.remote);
  346. this._pc.connectDataConnection(message.local, message.remote);
  347. };