connection.js 9.6 KB

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